2016-09-13 65 views
0

我想將幾個表連接在一起,其中一個表是同一個表上的同一個連接,具有不同的條件。我在查詢中獲得輸出,但不在統一的一行上。例如:SQL加入問題

select distinct rfp.id, title, bidtype, rfp.createdon as '#1', s.finishedDt as '#2', c.id as 'Contract #', supp.rfp_contr_supplier_name, es.suppdate as '#3', es2.suppdate as '#4' 
    from TBL_RFP_Ideas_NEW rfp 
left join tbl_rfp_senior s on rfp.id = s.ideaid 
left join rfp_contract c on rfp.id = c.ideaid 
inner join supplier_view supp on contractnbr = c.id 
left join TBL_EmpMaster_Full emp on rfp.sponsor_empid = emp.empid 
left join rfp_events e on rfp.id = e.ideaid 
left join rfp_events_suppliers es on e.id = es.event_id and e.heading = '4' and e.description = 'Master Agreement effective date' 
left join rfp_events_suppliers es2 on e.id = es2.event_id and e.heading = '5' and e.description = 'Master Agreement Rollout date' 
where rfp.id = '683311' 
group by rfp.id, title, bidtype, rfp.createdon, s.finishedDt, c.id, supp.rfp_contr_supplier_name, es.suppdate, es2.suppdate, e.description 

This gets output with the following Query

我能詳細一些桌子上的架構如果需要的話,但是聯接幾乎解釋瞭如何通過內置。我希望我失去了一些瘋狂的小事。任何幫助表示讚賞!

+1

您是否知道'distinct'在整行而不是在'rfp.id'上運行? –

+0

提及您的原始數據以及您的結果如何? –

+1

如果您打算使用「group by」,那麼您應該在select語句中使用某些聚合函數(如Min或Max)。然後從「group by」中刪除聚合函數中使用的字段。然後刪除「DISTINCT」,因爲你的「group by」刪除重複項,而「distinct」是多餘的。 –

回答

2

出現多行是因爲tbl_rfp_senior中有3條記錄與該ID匹配,並且在rfp_events中也可能有3條記錄(很難說沒有數據,您需要爲您的連接添加額外條件以消除額外行(例如,deactivation_date不是null?或者active = 1是一些想法),或者使用min和max或者其他一些總和(如sum)來獲得感興趣的單個結果並從分組中刪除這些字段。分組都是目前有代碼的氣味:-)

爲了幫助調試這個問題,我會開始選擇*並擺脫組,並確定多行來自哪裏和你需要做什麼聚集。

+0

這是一個好主意。我會試試這個。非常感謝! – slevin37

0
select distinct 
     rfp.id, title, bidtype, rfp.createdon as '#1', s.finishedDt as '#2', c.id as 'Contract #', supp.rfp_contr_supplier_name, es.suppdate as '#3', es2.suppdate as '#4' 
from 
     TBL_RFP_Ideas_NEW rfp 
     left join 
     (
      Select distinct ideaid,finishedDt 
      From tbl_rfp_senior 
     )s 
     on rfp.id = s.ideaid 
     left join 
     rfp_contract c 
     on rfp.id = c.ideaid 
     inner join 
     supplier_view supp 
     on contractnbr = c.id 
     left join 
     TBL_EmpMaster_Full emp 
     on rfp.sponsor_empid = emp.empid 
     left join 
     rfp_events e 
     on rfp.id = e.ideaid 
     left join 
     rfp_events_suppliers es 
     on e.id = es.event_id and e.heading = '4' and e.description = 'Master Agreement effective date' 
     left join 
     rfp_events_suppliers es2 
     on e.id = es2.event_id and e.heading = '5' and e.description = 'Master Agreement Rollout date' 
where rfp.id = '683311' 
group by rfp.id, title, bidtype, rfp.createdon, s.finishedDt, c.id, supp.rfp_contr_supplier_name, es.suppdate, es2.suppdate, e.description