0

I have a MS SQL query that joins multiple tables and an example of the results are:

EmailAddress          Column2                                      
--------------------- ----------------
sean@abc.com          Value1                                     
sean@abc.com          Value2
test@abc.com          Value5 


What I really want to achieve are the following results:


EmailAddress          Column2                                      
--------------------- ------------------
sean@abc.com          Value1, Value2
test@abc.com          Value5 

There are other columns that are identical for each row with the same email address. Can anyone help me with the SQL to return distinct email addresses and concatenate the column2 information?

Thanks for any feedback.

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
Sean
  • 2,453
  • 6
  • 41
  • 53

3 Answers3

1

Try the answer to this question

Community
  • 1
  • 1
Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
0

In SQL Server 2005+:

WITH    q AS
        (
        SELECT  'sean@abc.com' AS address, 'Value1' AS value
        UNION ALL
        SELECT  'sean@abc.com', 'Value2'
        UNION ALL
        SELECT  'test@abc.com', 'Value5'
        )
SELECT  (
        SELECT  CASE WHEN ROW_NUMBER() OVER (ORDER BY value) > 1 THEN ', ' ELSE '' END + value
        FROM    q qi
        WHERE   qi.address = qo.address
        FOR XML PATH('')
        )
FROM    (
        SELECT  DISTINCT address
        FROM    q
        ) qo
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
0

Same answer from Jeremy, but I would use the other answer with XML PATH trick

Community
  • 1
  • 1
van
  • 74,297
  • 13
  • 168
  • 171