2007年12月27日 星期四

同筆數之特定欄位字串合併

SQL 資料表Select查詢後,如何進行同筆數之特定欄位字串合併?
例如:
id memo
1 m1
1 m2
2 m3
2 m4
3 m5
3 m6
合併後變成:
id memo
1 m1m2
2 m3m4
3 m5m6
解答:---------------------------

DECLARE @table TABLE (id nvarchar(4), memo nvarchar(4))
INSERT INTO @table (id, memo)VALUES ('1', 'm1');
INSERT INTO @table (id, memo)VALUES ('1', 'm2');
INSERT INTO @table (id, memo)VALUES ('2', 'm3');
INSERT INTO @table (id, memo)VALUES ('2', 'm4');
INSERT INTO @table (id, memo)VALUES ('3', 'm5');
INSERT INTO @table (id, memo)VALUES ('3', 'm6');

SELECT T1.id,
(
SELECT memo + ''
FROM @table T2
WHERE T2.id = T1.id
ORDER BY memo
FOR XML PATH('')
) AS memo
FROM @table T1
GROUP BY id
-----------------------------

沒有留言: