--*******************************************************************************************
表结构,数据如下:
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc
需要得到结果:
id values
------ -----------
1 aa,bb
2 aaa,bbb,ccc
即:group by id, 求 value 的和(字符串相加)
create table tb(id int, value varchar(10))
insert into tb values(1, ‘aa‘)
insert into tb values(1, ‘bb‘)
insert into tb values(2, ‘aaa‘)
insert into tb values(2, ‘bbb‘)
insert into tb values(2, ‘ccc‘)
go
select id, [values]=stuff((select ‘,‘+[value] from tb t where id=tb.id for xml path(‘‘)), 1, 1, ‘‘)
from tb
group by id
/*
id values
----------- --------------------
1 aa,bb
2 aaa,bbb,ccc
(2 row(s) affected)
*/
drop table tb
最全介绍参考:https://www.cnblogs.com/yasuo2/p/6433697.html