CREATE TABLE #TEST
(A VARCHAR(10) NULL,B VARCHAR(MAX) NULL)
INSERT INTO #TEST
SELECT "A","A001"
UNION ALL
SELECT "A","A002"
UNION ALL
SELECT "A","A003"
UNION ALL
SELECT "B","B001"
UNION ALL
SELECT "B","B002"
SELECT * FROM #TEST
--先来看一个简单的,效果如下图所示:
SELECT STUFF((SELECT ","+B FROM #TEST FOR XML PATH("")),1,1,"")
---------------------------------------------------------------
--再来个我们想要的,效果见下图:
SELECT DISTINCT t1.A,
REPLACE((SELECT B AS [data()] FROM #TEST t2 WHERE t1.A=t2.A FOR XML PATH(""))," ",",") AS B
FROM #TEST t1
---------------------------------------------------------------