Multiple SQL rows merge into single row if the id is same

Multiple SQL rows merge into single row if the Code is same


Example:
Create table #user (Code int,username varchar(25))

insert into #user (Code,username) values (1,'Subha')
insert into #user (Code,username) values (1,'Shree')
insert into #user (Code,username) values (1,'Devi')
insert into #user (Code,username) values (2,'Rani')
I have table like ..
select * from #user
Result:

Solution:

Lets combine the Username(comma separated values) with respect to the Code.

SELECT Distinct Code
, STUFF((SELECT ', ' + A.username FROM #user A
Where A.Code=B.Code FOR XML PATH('')),1,1,'') As UserColl
From #user B
Group By Code, username
Example

Post a Comment

0 Comments