如何在连接多个表时使用 GROUP BY 连接字符串?
Posted
技术标签:
【中文标题】如何在连接多个表时使用 GROUP BY 连接字符串?【英文标题】:How to use GROUP BY to concatenate strings while joining multiple tables? 【发布时间】:2014-06-13 16:43:49 【问题描述】:我要根据TechnicianName
将多个表中的一个列值加入到行中:
我有 4 张桌子 easy_tbljobcard
、 easy_tbltechnician
和 easy_tblproblem
和 easy_tbltechnicianMaster
我在第二列从easy_tbltechnicianMaster
得到TechnicianName
,其中technicianId
存在于easy_tbltechnician
我希望 STUFF
在我的查询的第三列 (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
查询结果:
╔══════════╦══════════════════╦═══════════════════╗
║ 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 ║
╚══════════╩══════════════════╩═══════════════════╝
上面的结果应该转换成这个:
╔══════════╦══════════════════╦═════════════════════════════════╗
║ CardID ║ TechnicianName ║ ProblemReported ║
╠══════════╬══════════════════╬═════════════════════════════════╣
║ 1 ║ AKBAR ║ PROBLEM A, PROBLEM B, PROBLEM C ║
║ 1 ║ ASANKA ║ PROBLEM A, PROBLEM B, PROBLEM C ║
╚══════════╩══════════════════╩═════════════════════════════════╝
如何在连接多个表时执行此操作?
SQLFiddle
【问题讨论】:
How to use GROUP BY to concatenate strings in SQL Server?的可能重复 @Clockwork-Muse 我认为它不是重复的.. 你能不能给我提供一个例子,你可以用分隔符将列分组在一行中,特别是在加入多个表时,正如我在加入多个表时所说的那样表格 【参考方案1】:您可以指定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('')
,然后将第一个逗号,
替换为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
【讨论】:
我在加入多个表时需要这个,怎么做 @Siddiq Baig : 你的问题太宽泛了。用你的复杂查询更新你的答案,例如,指定你需要在哪里查询STUFF
等等。
@Siddiq Baig :考虑到唯一的反馈是“它不工作”,我现在很难理解出了什么问题。拿我的 sql fiddle,用你的三个表更新它,在此处插入必要的数据并发布。
抱歉回复晚了..我已经用 SQL Fiddle 更新了我的问题
让我们continue this discussion in chat.以上是关于如何在连接多个表时使用 GROUP BY 连接字符串?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 PostgreSQL 'group by' 查询中连接字符串字段的字符串?