question

ivric avatar image
ivric asked

SQL Table column values side by side in one column

I have one table ManagerID|EmpID ------------------ M01 | 100 | ------------------ M01 | 101 | ------------------ M02 | 102 | ------------------ M02 | 103 | ------------------ M02 | 104 | ------------------ M03 | 105 | ------------------ M04 | 106 | ------------------ I need it to look like the following: ManagerID| EmpID ------------------------- M01 | 100,101 | ------------------------- M02 | 102,103,104 | ------------------------- M03 | 105 | ------------------------- M04 | 106 | -------------------------
sqltsqlsql serverhierarchical-query
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Magnus Ahlkvist avatar image
Magnus Ahlkvist answered
You can use FOR XML PATH in a correlated subquery to create a comma separated list. CREATE TABLE #emp( ManagerID CHAR(3),EmpID INT); INSERT #emp (managerid,empid) values ('M01',100), ('M01',101), ('M02',102), ('M02',103), ('M02',104), ('M03',105), ('M04',106); SELECT DISTINCT Managerid, STUFF((SELECT ',' + CAST(empid AS VARCHAR(3)) FROM #emp e2 WHERE e2.managerid=e.managerid FOR XML PATH('')),1,1,'') FROM #emp e
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Magnus Ahlkvist avatar image Magnus Ahlkvist commented ·
...and from SQL Server 2017 you can use the STRING_AGG aggregate function to accomplish the same. Something like this: SELECT ManagerID, STRING_AGG(CAST(empid as varchar(3)),',') FROM #emp GROUP BY ManagerID;
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.