DIEA
您不能确定在子查询中没有order by语句的情况下串联的字符串的顺序。该.value('.', 'varchar(max)')部分用于处理Label包含XML不友好字符(如)的情况&。declare @T table(Response_ID int, Label varchar(50))insert into @T values(12147, 'It was not clear'),(12458, 'Did not Undersstand'),(12458, 'Was not resolved'),(12458, 'Did not communicate'),(12586, 'Spoke too fast'),(12587, 'Too slow')select T1.Response_ID, stuff((select ','+T2.Label from @T as T2 where T1.Response_ID = T2.Response_ID for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as Labelfrom @T as T1group by T1.Response_ID
侃侃尔雅
DECLARE @Results TABLE(Response_ID INT, Label VARCHAR(80));INSERT @Results(Response_ID, Label)SELECT 12147,'It was not clear'UNION SELECT 12458,'Did not Undersstand'UNION SELECT 12458,'Was not resolved'UNION SELECT 12458,'Did not communicate'UNION SELECT 12586,'Spoke too fast'UNION SELECT 12587,'Too slow';WITH x AS ( SELECT Response_ID FROM @Results GROUP BY Response_ID)SELECT x.Response_ID, Label = STUFF((SELECT ',' + Label FROM @Results WHERE Response_ID = x.Response_ID FOR XML PATH('')), 1, 1, '') FROM x;