Advertisements
Home > Sql Server > SQL Server : GROUP BY clause to get comma-separated values [duplicate]

SQL Server : GROUP BY clause to get comma-separated values [duplicate]


The original 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 by ReportId, but all the email should be comma separated. So the result should be:
ReportId     Email
1            a@a.com, c@c.com
2            b@b.com
3            d@d.com, e@e.com


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

Hope this help !

Advertisements
Categories: Sql Server
  1. Nayan
    December 4, 2013 at 4:06 am

    its really use full to me, thanks for this blog..

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: