SQL Server: GROUP BY clause to get comma separated values

Possible duplicate:
SQL group_concat function in SQL Server

I want to create a query, but somehow I cannot do it. Can anyone help me here?

Initial data

ID ReportId Email 1 1 a@a.com 2 2 b@b.com 3 1 c@c.com 4 3 d@d.com 5 3 e@e.com 

I want to group ReportId , but all emails should be separated by a comma. Thus, the result should be:

 ReportId Email 1 a@a.com, c@c.com 2 b@b.com 3 d@d.com, e@e.com 

What is the best way to do this?

I am trying a group by clause, but if there is any other thing, then I am also ready to implement this. I really appreciate your time and help with this. Thank.

+47
sql sql-server-2008
01 Oct
source share
2 answers

try the following:

 SELECT ReportId, Email = STUFF((SELECT ', ' + Email FROM your_table b WHERE b.ReportId = a.ReportId FOR XML PATH('')), 1, 2, '') FROM your_table a GROUP BY ReportId 


SQL script demonstration

+102
01 Oct '12 at 6:40
source share
β€” -
 SELECT [ReportId], SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList FROM ( SELECT DISTINCT [ReportId] FROM Table1 ) a CROSS APPLY ( SELECT [Email] + ', ' FROM Table1 AS B WHERE A.[ReportId] = B.[ReportId] FOR XML PATH('') ) D (EmailList) 

SQLFiddle Demo

+11
01 Oct '12 at 6:40
source share



All Articles