SQL - 字符串连接分组WITHOUT DISTINCT

时间:2017-08-02 08:13:27

标签: sql sql-server sql-server-2012

我想知道这是否可行 - 我有一张这样的表:

pk int, num int, name varchar(1)
1       1        'a'
2       1        'b'
3       1        'c'
4       1        'd'
5       1        'e'
6       2        'f'
7       2        'g'
8       2        'h'
9       2        'i'
10      2        'j'

我想要一个这样的输出,不使用DISTINCT子句:

num  result
1    a,b,c,d,e
2    f,g,h,i,j

以下是用于测试的ddl语句:

declare @tbl table (pk int, num int, name varchar(1))
insert into @tbl select 1, 1, 'a'
insert into @tbl select 2, 1, 'b'
insert into @tbl select 3, 1, 'c'
insert into @tbl select 4, 1, 'd'
insert into @tbl select 5, 1, 'e'
insert into @tbl select 6, 2, 'f'
insert into @tbl select 7, 2, 'g'
insert into @tbl select 8, 2, 'h'
insert into @tbl select 9, 2, 'i'
insert into @tbl select 10, 2, 'j'

以下查询有效,但如果可能,我想删除DISTINCT子句:

select DISTINCT num, stuff((select ',' + name from @tbl where num = t.num for xml path('')), 1, 1, '')
from @tbl t

知道如何在SQL 2012 +中执行此操作吗?

2 个答案:

答案 0 :(得分:1)

尝试这个我认为它会正常工作

select num, group_concat(name) from table_name group by num;

答案 1 :(得分:1)

如果您没有所需的num值列表,则可以创建一个。{p>一种相当愚蠢的方式是:

select t.num,
       stuff( (select ',' + name
               from @tbl t2
               where t2.num = t.num
               for xml path('')
              ), 1, 1, '')
from (values (1), (2)) as t(num);

更常见的是,这将写成:

select t.num,
       stuff( (select ',' + name
               from @tbl t2
               where t2.num = t.num
               for xml path('')
              ), 1, 1, '')
from (select distinct num from @tbl) t;