SQL Server如何将Id相同的字段合并,并且以逗号隔开

需要用到stuff函数:

例: 

         id             name           1               张三           1               李四           2               王五           2               赵六结果:          Id          name           1          张三,李四           2          王五,赵六

创建测试表及插入数据:

1
2
3
4
5
6
7
8
create table test
(id int,
name varchar(10))
 
insert into test values (1,' 张三')
insert into test values (1,' 李四')
insert into test values (2,王五')
insert into test values (2,' 赵六')

执行语句:

1
2
3
select id,stuff((select ','+name from test 
where a.id=id for xml path('')),1,1,''as name
from test as group by id

执行结果截图:

 

 

posted @ 2018-06-11 14:42  Mr.石  阅读(484)  评论(0编辑  收藏  举报