我正在根据TechnicianName
加入多个表,其中我希望将一个列值放入行中:
我有4个表easy_tbljobcard
,easy_tbltechnician
和easy_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 ║
╚══════════╩══════════════════╩═══════════════════╝
如何在连接多个表时执行此操作?
答案 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