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

时间:2014-06-13 16:43:50

标签: sql sql-server sql-server-2008 tsql sql-server-group-concat

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

  • 我有4个表easy_tbljobcardeasy_tbltechnicianeasy_tblproblem以及easy_tbltechnicianMaster

  • 我从TechnicianName的{​​{1}}第二列获得easy_tbltechnicianMaster technicianId

  • 我想在查询的第3栏中easy_tbltechnician STUFF

当前SQL语句:

p.ProblemReported

查询结果:

 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

上述结果应转换为:

╔══════════╦══════════════════╦═══════════════════╗
║  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     ║
╚══════════╩══════════════════╩═══════════════════╝

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

SQLFiddle

1 个答案:

答案 0 :(得分:11)

您可以指定CTE – common table expression来存储您的临时结果:

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 )

然后select从中t.techName并使用t.CardID将所有列值与同一行for xml path(''),连接起来,然后替换第一个逗号{{1与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

SQLFiddle