2013-12-23 34 views
0

在表中有两行,一个公共ID和不同的值。如何将这两行连接到SQL中的一列中

例:

ID Response 
============= 
1 one 
1 two 
2 three 
3 four 

我怎样才能这两行Concat的成一列。

select 
    case 
     when multiple then row1 + ',' + row2 
     else Response 
    end as response 
from testtable 

预期输出:

response 
========== 
one,two  
three 
four 

SQL专家:我怎么能代替row1 + ',' + row2使此查询工作?

回答

2
Select Id, Stuff((Select ','+Response from TableName B where B.Id=A.Id for Xml Path('')),1,1,'') as Response from TableName A 
group By Id; 

Sql Fiddle Demo

+0

您可以通过使用值的方法改善这种答案:(... FOR XML ...)值(“[N] VARCHAR(MAX) '' )。 [SQL Fiddle](http://www.sqlfiddle.com/#!3/e3db5/1) –

0
Declare @t table(id int,col1 varchar(20)) 
insert into @t values(1,'one'),(1, 'two'),(2, 'three'),(3, 'four') 
select distinct a.id, 
stuff((select ','+col1 from @t b where b.id=a.id for xml path('')),1,1,'')col1 
from @t a 
相关问题