0

可能重复:
SQL 查询以逗号分隔符以及 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  

怎么可能做到?

4

1 回答 1

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

获得正确的数据集后,只需创建一个简单的表格来显示结果即可。

于 2013-01-18T11:17:23.437 回答