2010-10-20 2 views
2

Imaginez que j'ai ce tableauSQL Server T-SQL concat globale

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

Comment puis-je obtenir un résultat comme celui-ci

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

TKS

+4

Utilisez [FOR XML PATH] (http://stackoverflow.com/questions/3824203/3841835#3841835). C'est une dupe plusieurs fois. –

Répondre

2

essayez ceci:

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 

OUTPUT:

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

(2 row(s) affected) 
0

Cette solution fonctionne sans avoir besoin de déployer à partir du fichier Visual Studio ou dll dans le serveur.

Copiez-collez et ça marche!

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)