2011年10月17日 星期一

Combine Multiple Columns And Records In MSSQL


In this example i am going to describe how to combine multiple columns and records in one column in MS SQL.

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



沒有留言: