shaoqin 发表于 2016-11-8 06:18:06

How to use GROUP BY to concatenate strings in SQL Server?

CREATE TABLE #YourTable ( INT, CHAR(1), INT)
INSERT INTO #YourTable (,,) VALUES (1,'A',4)
INSERT INTO #YourTable (,,) VALUES (1,'B',8)
INSERT INTO #YourTable (,,) VALUES (2,'C',9)
SELECT
,
STUFF((
SELECT ', ' + + ':' + CAST( AS VARCHAR(MAX))
FROM #YourTable
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())','VARCHAR(MAX)')
,1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY ID
DROP TABLE #YourTable
页: [1]
查看完整版本: How to use GROUP BY to concatenate strings in SQL Server?