Friday, March 14, 2014

Combine multiple rows of table into single row in SQL Server

Here I will explain about how to get multiple rows data  and combine that data into single row using SQL query in SQL Server 2005/2008.

Example:

I have created one table with named tbl_User like below :











In the tbl_user Table I have inserted few records as shown below












So now we need to combine user names(UserName) based on group name(GroupName) using
 FOR XML PATH .

 



SELECT
   STUFF((SELECT ', ' + cast(UserID as varchar(20)) 
   from tbl_user t2
   where t1.GroupName = t2.GroupName
   FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
   ,1,2,'') 'User ID'
   ,
   STUFF((SELECT ', ' + cast(UserName as varchar(20))  
   from tbl_user t2
   where t1.GroupName = t2.GroupName  
   FOR XML PATH(''),TYPE ).value('.', 'NVARCHAR(MAX)')
   ,1,2,'') 'Group of name'
   , t1.GroupName
from tbl_user t1
Group By t1.GroupName



After execute above query we got following result :





No comments:

Post a Comment