我正在使用MS Sql server 2008 R2。 我有一个查询,给我这样的输出
Col1....Col2
CV1.....AV1
CV1.....AV2
CV2.....AV3
CV2.....AV4
查询
select Tab1.Col1, Tab2.Col2
from Table1 Tab1
JOIN Table2 Tab2 on Tab1.PKID = Tab2.FKID
我想要的是Col1和Col2中每个不同值的一行所有与col1相关的值与逗号或管道分隔符
Col1....Col2
CV1.....AV1,AV2
CV2.....AV3,AV4
有人可以帮我吗?
基本上我需要像my sql
中可用的group_concat之类的东西答案 0 :(得分:1)
CREATE TABLE a(
Col1 varchar(50),
Col2 varchar(20));
INSERT INTO a (Col1,Col2) values ('CV1','AV1');
INSERT INTO a (Col1,Col2) values ('CV1','AV2');
INSERT INTO a (Col1,Col2) values ('CV2','AV3');
INSERT INTO a (Col1,Col2) values ('CV2','AV4');
with t as (SELECT Col1,(CAST(Col2 AS nvarchar (12))) as col2 from a )
Select distinct T2.Col1,
substring((Select ',' + T1.col2 AS [text()]
From t T1
Where T1.Col1 = T2.Col1
ORDER BY T1.Col1
For XML PATH ('')),2, 100) [col2]
From t T2
尝试此查询。我在sql server中这样做。检查sqlfidddle