2
想象我有這個表SQL Server的T-SQL Concat的總
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結果
想象我有這個表SQL Server的T-SQL Concat的總
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結果
試試這個:
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)
該解決方案無需從服務器中的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)
用[FOR XML PATH](http://stackoverflow.com/questions/3824203/3841835#3841835)。這是一個重複多次。 – 2010-10-20 13:20:03