需要用到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,' 赵六') |
执行语句:
|
1
2
3
|
select id,stuff((select ','+name from test where a.id=id for xml path('')),1,1,'') as namefrom test as a group by id |
执行结果截图:
