2011-02-04 146 views
2

嗨 有人可以帮我解决以下问题。我需要写一个MS SQL statment才达到以下几点:SQL Group by concat

表1有2列:Column1Column2

数据table1中看起来像

Column1 Column2 
1   a 
1   b 
1   c 
2   w 
2   e 
3   x 

我需要我的SQL statment输出如下

Column1 Column2 
1   a, b, c 
2   w, e 
3   x 

所以换句话说,我需要按column1进行分组,并将column2值连接在一起,并用逗号分隔。请注意,这将需要能够在SQL Server 2000及以上

+0

对不起,我试图显示与两栏(Column1和Column2)的示例表,不知道wh Ÿ它没有正常结果 – 2011-02-04 02:53:03

回答

4

运行,你可以创建一个函数来Concat的值

create function dbo.concatTable1(@column1 int) returns varchar(8000) 
as 
begin 
declare @output varchar(8000) 
select @output = coalesce(@output + ', ', '') + column2 
from table1 
where column1 = @column1 and column2 > '' 
return @output 
end 
GO 

因此,假如你有此表

create table table1 (column1 int, column2 varchar(10)) 
insert table1 select 1, 'a' 
insert table1 select 1, 'b' 
insert table1 select 1, 'c' 
insert table1 select 2, 'w' 
insert table1 select 2, 'e' 
insert table1 select 3, 'x' 
GO 

你像这样使用它

select column1, dbo.concatTable1(column1) column2 
from table1 
group by column1