根据ID连接值

时间:2011-07-06 21:36:25

标签: sql sql-server sql-server-2005 tsql sql-server-2008

我有一个名为Results的表,数据如下:

Response_ID    Label
12147          It was not clear
12458          Did not Undersstand
12458          Was not resolved
12458          Did not communicate
12586          Spoke too fast
12587          Too slow

现在我希望输出每个ID显示一行,Label中的值连接起来并用逗号分隔

我的输出应该如下:

Response_ID    Label
12147          It was not clear
12458          Did not Undersstand,Was not resolved,Did not communicate
12586          Spoke too fast
12587          Too Slow

我该怎么做:

4 个答案:

答案 0 :(得分:10)

如果子查询中没有order by语句,则无法确定连接的字符串的顺序。 .value('.', 'varchar(max)')部分用于处理Label包含 XML-unfriendly 字符的情况,例如&

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 Label
from @T as T1
group by T1.Response_ID

答案 1 :(得分:1)

检查下面的链接,它通过许多不同的解决方案解决您的问题

http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

答案 2 :(得分:1)

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;

答案 3 :(得分:-1)

考虑一下,这是非常有效的:

http://jerrytech.blogspot.com/2010/04/tsql-concatenate-strings-1-2-3-and.html

避免使用XML函数,因为它们不具备性能。

这需要付出一些努力来实现,但数百万行=>毫秒运行。