2015-10-03 65 views
2

我在SQL 2008數據庫中有兩個表,當我運行查詢時需要合併兩列。在查詢中組合兩個表

表1我需要Emply_IDEmply_NameEmply_HomeDeptEmply_Shift

表2我需要Emply_IDEmply_OtherDeptEmply_AltShift

我倒是要能夠做的是生產單排,結合HomeDeptOtherDept一起ShiftAltShift在一起。所以,我最終會與

00124|John Doe|Loading,Packing,Shipping|Shift1,Shift2,Shift3 
+1

和什麼問題? –

回答

3

這應該符合您的期望:

SELECT t.EmplyId, 
     t.Emply_name, 
     CONCAT(t.Emply_HomeDept, ',' , x.otherDept) AS FullDept, 
     CONCAT(t.Emply_Shift, ',' , x.AltShift) AS FullShift, 
FROM 
    Table1 t 
    LEFT JOIN (
    SELECT t2.EmplyId, 
      (SELECT t3.OtherDept + ',' AS [text()] 
      FROM table2 t3 
      WHERE t3.EmplyId = t2.EmplyId 
      FOR XML PATH ('') 
      ) AS otherDept, 
      (SELECT t4.AltShift + ',' AS [text()] 
      FROM table2 t4 
      WHERE t4.EmplyId = t2.EmplyId 
      FOR XML PATH ('') 
      ) AS AltShift   
    FROM 
     Table2 t2) x 
    ON t.Emply_Id = x.EmplyId 
+0

謝謝你的解決方案Rafal工作得很好 – JamesHussey

+0

我很高興它適合你。 –

+0

我希望你會接受我的回答;) –