Sqlserver 中如何通過group by 實現分組合並
--------------------第一步:新建表:Test----------------------------
CREATE TABLE test(id varchar(50), [values] varchar(10))
INSERT test SELECT '001', 'aa'
UNION ALL SELECT '001', 'bb'
UNION ALL SELECT '002', 'aaa'
UNION ALL SELECT '002', 'bbb'
UNION ALL SELECT '002', 'ccc';
具體實現的方法:
方法①
SELECT id,
[values] =
stuff(b.[values].value('/R[1]', 'nvarchar(max)'),
1,
1,
'')
FROM (SELECT id
FROM test
GROUP BY id) a
CROSS apply (
SELECT [values] =(
SELECT N',' + [values] FROM test
WHERE id = a.id
FOR XML PATH(''), ROOT('R'), TYPE
)
) b;
方法②:
SELECT id, data=STUFF((SELECT ','+[values] FROM test t WHERE id=t1.id FOR XML PATH('')), 1, 1, '')
FROM test t1
GROUP BY id
最後結果:
id data
------------- ----------------------
001 aa,bb
002 aaa,bbb,ccc
(2 行受影響)
不想要test的時候:drop table test