我在SQL 2008数据库中有两个表,我需要在运行查询时合并两列。
表1 我需要Emply_ID
,Emply_Name
,Emply_HomeDept
,Emply_Shift
表2 我需要Emply_ID
,Emply_OtherDept
,Emply_AltShift
。
我能够做的是生成一行,将HomeDept
和OtherDept
放在一起,Shift
和AltShift
放在一起。 我最终会以
00124|John Doe|Loading,Packing,Shipping|Shift1,Shift2,Shift3
答案 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