Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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            [email protected]
2     2            [email protected]
3     1            [email protected]
4     3            [email protected]
5     3            [email protected]

I want to group by ReportId, but all the email should be comma separated. So the result should be:

ReportId     Email
1            [email protected], [email protected]
2            [email protected]
3            [email protected], [email protected]

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.

like image 568
user867198 Avatar asked Oct 01 '12 06:10

user867198


People also ask

How do you get records with comma separated Values in SQL query?

In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.

How do you remove duplicates from a comma separated string in SQL?

Solution 1 Available in SQL Server 2016 and later. -- Sort the values: SELECT value FROM STRING_SPLIT(@temp, ',') ORDER BY value; -- Remove duplicates: SELECT DISTINCT value FROM STRING_SPLIT(@temp, ',');


2 Answers

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

like image 60
Joe G Joseph Avatar answered Sep 30 '22 09:09

Joe G Joseph


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

like image 28
John Woo Avatar answered Sep 30 '22 07:09

John Woo