116

Possible Duplicate:
SQL group_concat function in SQL Server

I am looking to create a query but somehow I am unable to do so. Can anyone please help me out here?

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

What is the best way to do this?

I am trying the group by clause but if there is any other thing then i am open to implement that also. I really appreciate your time and help on this. Thank you.

Community
  • 1
  • 1
user867198
  • 1,588
  • 3
  • 16
  • 31
  • and [sql-group-concat-function-in-sql-server](http://stackoverflow.com/questions/8868604/sql-group-concat-function-in-sql-server) – gts Oct 01 '12 at 06:48
  • Starting with SQL Server 2017 you can use `SELECT ReportId, STRING_AGG(a.Email, ', ') as Email FROM your_table a GROUP BY ReportId` – Paul Nakitare Oct 28 '22 at 07:19

2 Answers2

218

try this:

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 fiddle demo

Joe G Joseph
  • 23,518
  • 5
  • 56
  • 58
26
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

GôTô
  • 7,974
  • 3
  • 32
  • 43
John Woo
  • 258,903
  • 69
  • 498
  • 492