在select查询中合并具有相同外键id值的列

时间:2016-02-22 14:20:42

标签: sql sql-server sql-server-2008

我有一张名为CARS(id,brand,owner)的表格。让我们假设所有者是外键,表中的数据是:

1   mercedes  Jack
2   mercedes  John
3   bmw       Jack
4   bmw       John
6   audi      Jack

我想要的是看到这样的输出:

1   mercedes, bmw, audi   Jack
2   mercedes, bmw         John

我该如何管理?我在下面写了这个查询,但它不能正常工作。任何帮助将不胜感激。

select CARS.id, CARS.brand, CARS.owner
from CARS 
inner join (Select c1.id, (c1.brand + ',' + c2.brand) from CARS c inner join CARS c2 
           on (c1.owner = c2.owner) where c1.brand <> c2.brand) as tempCars
on (CARS.id = tempCars.id)

我无法正确管理合并过程..

编辑:我的帖子看起来类似于Tab Alleman提到的帖子。我在问这个问题之前就已经看过了,但答案对我来说并不是那么清楚,所以我仍然无法弄清楚如何修改我的查询来实现我的目标。任何额外的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

试试这样:

DECLARE @tbl TABLE(id INT, brand VARCHAR(100),owner VARCHAR(100));
INSERT INTO @tbl VALUES
 (1,'mercedes','Jack')
,(2,'mercedes','John')
,(3,'bmw','Jack')
,(4,'bmw','John')
,(6,'audi','Jack');

WITH DistinctOwners AS
(
    SELECT DISTINCT owner 
    FROM @tbl
)
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS inx
      ,STUFF((
        SELECT ',' + innerTbl.brand
        FROM @tbl AS innerTbl 
        WHERE innerTbl.owner=do.owner
        FOR XML PATH('')
       ),1,1,'') AS brands
       ,do.owner
FROM DistinctOwners AS do     

结果

1   mercedes,bmw,audi   Jack
2   mercedes,bmw        John