在查询中组合两个表

时间:2015-10-03 21:17:28

标签: sql sql-server sql-server-2008

我在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 个答案:

答案 0 :(得分: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