答案 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