1 DECLARE @tb TABLE(id int, value varchar(10)) 2 insert into @tb values(1, ‘aa‘) 3 insert into @tb values(1, ‘bb‘) 4 insert into @tb values(2, ‘aaa‘) 5 insert into @tb values(2, ‘bbb‘) 6 insert into @tb values(2, ‘ccc‘) 7 8 -- 查询处理 9 SELECT * FROM(SELECT DISTINCT id FROM @tb) A OUTER APPLY( 10 SELECT [values]= STUFF(REPLACE(REPLACE( 11 ( 12 SELECT value FROM @tb N 13 WHERE id = A.id 14 FOR XML AUTO 15 ), ‘<N value="‘, ‘,‘), ‘"/>‘, ‘‘) ,1,1,‘‘) 16 ) N
输出
id values
----------- -----------
1 aa,bb
2 aaa,bbb,ccc
SELECT STUFF((SELECT ‘,‘+name FROM 表名 for xml path(‘‘)),1,1,‘‘)