02 February, 2011

Combine Multiple Records Comma Separated In One Column MSSQL 2005

In this example i am going to describe how to combine multiple records in a column in MS SQL into one record comma separated.

Here is the scenario

I have a table having Employees names and their respective Department names, now i want to show Employees names separated by comma into one column and respective Department name in another column.

My table schema is shown in the image below



And this is Data into table



I want output in following format
Department---------------FirstName
IT----------------------amiT,Emp1,Emp5
Admin-------------------Shobhit, Emp3,Emp7
and so on

To get this desired result we need to write below mentioned query
SELECT DISTINCT Department,
EmpNames = substring( ( SELECT ', ' + FirstName
FROM Employees e2
WHERE e2.Department = e1.Department FOR XML path(''), elements),2,500)
FROM Employees e1

And the output of this SQL Query would be

No comments:

Post a Comment