需要用到stuff函数:
例:
id name
1 张三
1 李四
2 王五
2 赵六
结果:
Id name
1 张三,李四
2 王五,赵六
创建测试表及插入数据:
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,' 赵六')
执行语句:
select id,stuff((select ','+name from test
where a.id=id for xml path('')),1,1,'') as name
from test as a group by id
执行结果截图:
select id,stuff((select ','+name from tb where a.id=id for xml path('')),1,1,'') as name
from tb as a group by id