可能重复:
SQL Query to get aggregated result in comma seperators along with group by column in SQL Server
我有两张桌子:
CarID | CarName | Color
------+----------+----------
1 | Ford | White
2 | Mitsu | Black
3 | Mitsu | Green
OwnerID | OwnerName | CarID
--------+-----------+-------
1 | John | 1
1 | John | 3
2 | Mark | 2
我需要一份以下报告:
CarName | Owners
--------+------------
Ford | John
Mitsu | John, Mark
怎么可能呢?
答案 0 :(得分:4)
在数据库级别构建正确的数据集最容易,例如:
SELECT
c.CarName,
STUFF
(
(
SELECT ',' + owner
FROM Owner o
WHERE c.carID = o.carID
ORDER BY owner
FOR XML PATH('')
), 1, 1, ''
) AS owners
FROM Car c
这将为每个汽车/颜色组合返回一行,因此还需要考虑的是是否要忽略颜色 - 然后您需要对汽车名称进行分组:
SELECT
c.CarName,
STUFF
(
(
SELECT ',' + owner
FROM (select cd.carname, o.owner from Owner o inner join Car cd on o.carID = cd.carID) o
WHERE c.CarName = o.CarName
ORDER BY owner
FOR XML PATH('')
), 1, 1, ''
) AS owners
FROM (select distinct carname from Car) c
一旦您获得了正确的数据集,只需创建一个简单的表来显示结果。