SQL - 使用Group By时逗号分隔数据

Wil*_*ill 3 sql t-sql concatenation coalesce

我正在使用SQL Server和TSQL:

我想要做的是在另一列上使用group by时在一列上使用逗号分隔值.见下面的数据示例.

col1 --- col2

1121     abc
1123     aee
1335     afg
1121     def
1121     abc

我想在"col1"上分组并计算记录数,但如果数据不同,我还想在col2上连接.例如,使用值"1121"作为参考,请参阅下面的数据输出.

qty --- col1 --- col2

3       1121     abc, def
1       1123     aee
1       1335     afg

我想过可能使用COALESCE,但我不确定如何在另一列上使用group by时实现它.

任何帮助将不胜感激.

dcp*_*dcp 5

这是一个完整的,经过测试的工作示例.

create table tmp (col1 varchar(100), col2 varchar(100));
insert into tmp values ('1121',    'abc');
insert into tmp values ('1123',    'aee');
insert into tmp values ('1335',    'afg');
insert into tmp values ('1121',    'def');
insert into tmp values ('1121',    'abc');

SELECT 
distinct r.col1,
       STUFF((SELECT distinct ','+ a.col2
               FROM tmp a
             WHERE r.col1 = a.col1
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''),
       (select COUNT(*) cnt from tmp a where r.col1 = a.col1) cnt
 FROM tmp r
Run Code Online (Sandbox Code Playgroud)

结果

1121    abc,def 3
1123    aee     1
1335    afg     1
Run Code Online (Sandbox Code Playgroud)

参考文献: 二手OMG小马答案在这里作为参考.