0

I have table like this:

ID      Name
--------------
1       Ritesh
1       Raj
1       Suraj
2       John
2       Sanjay
2       Max
3       Dinesh
3       Dheeraj

I want to join the column values of column Name using column ID having same values of Id

The output should be in a new table with a single column:

NewColumn
------------------
Ritesh,Raj,Suraj
John,Sanjay,Max
Dinesh,Dheeraj

The first three names have same id as 1 and same as for id 2 and 3

Any help?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ritesh
  • 13
  • 8
  • 1
    Possible duplicate of [Simulating group\_concat MySQL function in Microsoft SQL Server 2005?](https://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005) – marc_s Jul 13 '17 at 16:54
  • Not getting a clear picture still. – Ritesh Jul 13 '17 at 18:11
  • Maybe this one will help? http://www.sqlservercentral.com/articles/comma+separated+list/71700/ – Sean Lange Jul 13 '17 at 18:56

1 Answers1

0

Try something like this.

;WITH CTE AS
(SELECT D1.ID, STUFF((SELECT ','+D2.NAME FROM DATA D2 FOR XML PATH('') WHERE D1.ID = D2.ID),1,1,'') AS NAME FROM DATA D1)
SELECT DISTINCT NAME FROM CTE
ADyson
  • 57,178
  • 14
  • 51
  • 63