如何在连接多个表时使用GROUP BY连接字符串?

Sid*_*aig 5 sql t-sql sql-server sql-server-2008 sql-server-group-concat

我正在加入多个表,我希望根据以下内容将一个列值放入行中TechnicianName:

  • 我有4个表easy_tbljobcard,easy_tbltechnicianeasy_tblproblemeasy_tbltechnicianMaster

  • 我得到TechnicianName第2列从easy_tbltechnicianMaster 哪里technicianId存在easy_tbltechnician

  • 我想STUFF在我的查询中的第3列(p.ProblemReported)

当前的SQL语句:

 SELECT j.CardID, 
      , (SELECT TechnicianName FROM easy_tbltechnicianMaster WHERE TechnicianID = t.technicianID) AS TechnicianName
      , p.ProblemReported 
 FROM easy_tbljobcard AS j 
 JOIN easy_technician AS t ON t.CardID = j.CardID  
 LEFT JOIN easy_tblproblem AS p ON p.CardID = t.CardID
Run Code Online (Sandbox Code Playgroud)

查询结果:

???????????????????????????????????????????????????
?  CardID  ?  TechnicianName  ?  ProblemReported  ?
???????????????????????????????????????????????????
?    1     ?      AKBAR       ?     PROBLEM A     ?
?    1     ?      AKBAR       ?     PROBLEM B     ?
?    1     ?      AKBAR       ?     PROBLEM C     ?
?    1     ?      ASANKA      ?     PROBLEM A     ?
?    1     ?      ASANKA      ?     PROBLEM B     ?
?    1     ?      ASANKA      ?     PROBLEM C     ?
???????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

上面的结果应转换成:

?????????????????????????????????????????????????????????????????
?  CardID  ?  TechnicianName  ?         ProblemReported         ?
?????????????????????????????????????????????????????????????????
?    1     ?      AKBAR       ? PROBLEM A, PROBLEM B, PROBLEM C ?
?    1     ?      ASANKA      ? PROBLEM A, PROBLEM B, PROBLEM C ?
?????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

如何在连接多个表时执行此操作?

SQLFiddle

pot*_*hin 11

您可以指定CTE - 公用表表达式来存储临时结果:

with cteTbl ( CardID
            , TechName
            , problemReported ) as ( 
select j.CardID
     , p.ProblemReported
     , ( select TechnicianName
         from easy_tbltechnicianMaster
         where TechnicianID =  t.technicianID ) as TechName
from easy_tbljobcard as j 
join easy_technician as t on t.CardID = j.CardID  
left join easy_tblproblem as p  on p.CardID = t.CardID )
Run Code Online (Sandbox Code Playgroud)

然后select从它和连接具有相同的所有列值t.techName,并t.CardID在一排用for xml path(''),之后更换第一个逗号,stuff:

select t.CardID
     , t.TechName
     , stuff( ( select ', ' + ProblemReported
                from cteTbl
                where TechName = t.TechName
                order by ProblemReported
                for xml path('') ), 1, 1, '') AS ProblemReported
from cteTbl t
group by t.TechName
       , t.CardID
Run Code Online (Sandbox Code Playgroud)

SQLFiddle