SQL Server T-SQL concat聚合

时间:2010-10-20 13:17:21

标签: sql-server tsql

想象一下,我有这张桌子

BirthDay     |Name
1-10-2010    | 'Joe'
2-10-2010    | 'Bob' 
2-10-2010    | 'Alice'

我怎样才能得到像这样的结果

BirthDay     |Name
1-10-2010    | 'Joe'
2-10-2010    | 'Bob', 'Alice 

TKS

2 个答案:

答案 0 :(得分:2)

试试这个:

set nocount on;
declare @t table (BirthDay datetime, name varchar(20))
insert into @t VALUES ('1-10-2010',     'Joe'  )
insert into @t VALUES ('2-10-2010',     'Bob'  )
insert into @t VALUES ('2-10-2010',     'Alice')
set nocount off

SELECT p1.BirthDay,
          stuff(
                   (SELECT
                        ', ' + p2.name  --use this if you want quotes around the names:  ', ''' + p2.name+''''
                        FROM @t p2
                        WHERE p2.BirthDay=p1.BirthDay
                        ORDER BY p2.name
                        FOR XML PATH('') 
                   )
                   ,1,2, ''
               ) AS Names
      FROM @t p1
     GROUP BY 
        BirthDay

输出:

BirthDay                Names
----------------------- ------------
2010-01-10 00:00:00.000 Joe
2010-02-10 00:00:00.000 Alice, Bob

(2 row(s) affected)

答案 1 :(得分:0)

此解决方案无需从Visual Studio或服务器中的dll文件进行部署即可运行。

复制粘贴并且工作正常!

http://groupconcat.codeplex.com/

dbo.GROUP_CONCAT(VALUE )
dbo.GROUP_CONCAT_D(VALUE ), DELIMITER )  
dbo.GROUP_CONCAT_DS(VALUE , DELIMITER , SORT_ORDER )
dbo.GROUP_CONCAT_S(VALUE , SORT_ORDER )