I am using SQL Server 2008. I have a table like below:
ID Name
1 a
1 b
2 c
3 d
I want output like below:
ID Name
1 a,b
2 c
3 d
I am using SQL Server 2008. I have a table like below:
ID Name
1 a
1 b
2 c
3 d
I want output like below:
ID Name
1 a,b
2 c
3 d
SELECT ID, Names = STUFF((SELECT N',' + Name
FROM dbo.TheTable AS x
WHERE x.ID = t.ID
ORDER BY Name
FOR XML PATH(''), TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1,1,'')
FROM dbo.TheTable AS t
GROUP BY ID;
On more modern versions (SQL Server 2017+), this is much tidier and more efficient:
SELECT ID, Names = STRING_AGG(Name, N',')
FROM dbo.TheTable
GROUP BY ID;
select id, (select itbl.name+','
from tblname itbl
where itbl.id=tbl.id
for xml path('')) name
from tblname tbl
group by id