由逗号分隔的SQL Server 2012列到单行

时间:2017-08-18 00:57:35

标签: sql sql-server row comma

我有一个包含SortOrder和DiagnosisCodes的表。

enter image description here

对于每组不同的SortOrders,我需要在一行中看到DiagnosisCodes。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

使用FOR XML PATH

DECLARE @diagnosis TABLE (id INT, diagnosiscode VARCHAR(10))
INSERT INTO @diagnosis VALUES
(1,'D50.9'),
(1,'M10.9'),
(1,'Z79.82'),
(2,'M81.0'),
(2,'Z85.3'),
(2,'Z90.710'),
(3,'M81.0'),
(3,'Z85.3'),
(3,'Z17.0')


SELECT t.id,
       STUFF(( SELECT ', ' + diagnosiscode
                FROM @diagnosis
                WHERE id = t.id
                FOR XML PATH(''),TYPE)
                .value('.','NVARCHAR(MAX)'),1,2,'') AS alldiagnosiscodes
  FROM @diagnosis t
 GROUP BY t.id
 ORDER BY t.id

结果

id  alldiagnosiscodes
1   D50.9, M10.9, Z79.82
2   M81.0, Z85.3, Z90.710
3   M81.0, Z85.3, Z17.0