在表格中有2行,其中包含一个公共ID和不同的值。
前:
ID Response
=============
1 one
1 two
2 three
3 four
如何将这两行连成一列。
select
case
when multiple then row1 + ',' + row2
else Response
end as response
from testtable
预期产出:
response
==========
one,two
three
four
SQL专家:如何替换row1 + ',' + row2
以使此查询有效?
答案 0 :(得分: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;
答案 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