连接具有相同值(不同列)的行的列值

时间:2011-06-20 15:26:25

标签: sql-server tsql group-concat

SQL Server 2005

我有一张表返回

ID  name    prop    value
--------------------------
1   one     Prop1   a
1   one     Prop1   b
1   one     Prop2   c
2   two     Prop1   d
2   two     Prop2   e

如何在其上运行选择以返回

ID  name    prop        value
-----------------------------
1   one     Prop1       a,b
1   one     Prop2       c
2   two     Prop1       d
2   two     Prop2       e

3 个答案:

答案 0 :(得分:3)

试试这个:

--Concatenation with FOR XML and eleminating control/encoded character expansion "& < >"
set nocount on;
declare @YourTable table (RowID int, RowName varchar(5), prop varchar(5), RowValue varchar(5))

insert into @YourTable VALUES (1,'one','Prop1','a')
insert into @YourTable VALUES (1,'one','Prop1','b')
insert into @YourTable VALUES (1,'one','Prop2','c')
insert into @YourTable VALUES (2,'two','Prop1','d')
insert into @YourTable VALUES (2,'two','Prop2','e')
set nocount off

SELECT
    t1.RowID,t1.RowName,t1.Prop
        ,STUFF(
                   (SELECT
                        ', ' + t2.RowValue
                        FROM @YourTable t2
                        WHERE t1.RowID=t2.RowID AND t1.RowName=t2.RowName AND t1.Prop=t2.Prop
                        ORDER BY t2.RowValue
                        FOR XML PATH(''), TYPE
                   ).value('.','varchar(max)')
                   ,1,2, ''
              ) AS ChildValues
    FROM @YourTable t1
    GROUP BY t1.RowID,t1.RowName,t1.Prop

输出:

RowID       RowName Prop  ChildValues
----------- ------- ----- ------------
1           one     Prop1 a, b
1           one     Prop2 c
2           two     Prop1 d
2           two     Prop2 e

(4 row(s) affected)

答案 1 :(得分:2)

SELECT ID
    ,name
    ,prop
    ,STUFF((SELECT ',' + value FROM table t2 WHERE t2.ID = t1.ID and t2.name = t1.name AND t2.prop = t1.prop FOR XML PATH('')),1,1,'') AS value
FROM table t1
GROUP BY ID,name,prop

请参阅: SQL Query to get aggregated result in comma seperators along with group by column in SQL Server

答案 2 :(得分:0)

SELECT T1.Name, T1.prop, T1.value+","+T2.value
From Table T1 INNER JOIN Table T2
ON T1.name = T2.name and T1.prop = T2.Prop and T1.value<>T2.value

这只适用于两个值。让我知道,我可以重写N值。