CREATE TABLE #TEST(A VARCHAR(10) NULL,B VARCHAR(MAX) NULL) INSERT INTO #TESTSELECT 'A','A001'UNION ALLSELECT 'A','A002'UNION ALLSELECT 'A','A003'UNION ...
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
---------------------------------------------------------------