0

I have the following table:

id, name
---------------
1, Customer 01
1, Customer 02
2, Customer 01
3, Customer 01
3, Customer 03

Is there an easy way to get result set like so:

id, customers
-----------------------
1, [Customer01],[Customer02]
2, [Customer01]
3, [Customer01,[Customer03]

I don't really need the brackets.

Rod
  • 14,529
  • 31
  • 118
  • 230
  • 3
    Possible duplicate of [How to use GROUP BY to concatenate strings in SQL Server?](http://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server) – Markus Jarderot Nov 15 '15 at 01:07

1 Answers1

1

use for xml path

------------------------------------------------------------
--Create temp table for testing
IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL 
    DROP TABLE #Temp

Create table #Temp
            (id Int, 
             name varchar(30))
Insert into #Temp
Values (1, 'Customer 01'),
       (1, 'Customer 02'),
       (2, 'Customer 01'),
       (3, 'Customer 01'),
       (3, 'Customer 03')

Query

SELECT DISTINCT
        o.id ,
        STUFF((SELECT  ',' + name
               FROM    #Temp AS i
               WHERE   i.ID = o.id
               FOR XML PATH('')),1,1,'') AS ConcatenatedName
FROM    #Temp AS o

Test is here SQL FIDDLE

Vasily
  • 5,707
  • 3
  • 19
  • 34