SQL Group by与concat

SQL Group by与concat,sql,tsql,sql-server-2000,group-by,concat,Sql,Tsql,Sql Server 2000,Group By,Concat,嗨 有人能帮我做以下事情吗。我需要编写MS SQL语句以实现以下目标: 表1有两列:Column1和Column2 表1中的数据如下所示 Column1 Column2 1 a 1 b 1 c 2 w 2 e 3 x 我需要我的Sql语句输出如下 Column1 Column2 1 a, b, c 2 w, e 3 x 换句话说,我需要按co

嗨 有人能帮我做以下事情吗。我需要编写MS SQL语句以实现以下目标:

表1有两列:
Column1
Column2

表1中的数据如下所示

Column1   Column2
1         a
1         b
1         c
2         w
2         e
3         x
我需要我的Sql语句输出如下

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

换句话说,我需要按column1分组,让column2的值用逗号分隔。请注意,这需要能够在SQL Server 2000及更高版本上运行

您可以创建一个函数来计算值

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

很抱歉,我试图显示包含两列(第1列和第2列)的示例表,但不确定为什么结果不正确。每行插入4个空格,它就会对齐。