Monday, July 19, 2010

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

Let's create with a table example:

create table mytable (id int identity(1,1), PersonID int, unit varchar(10))
insert into mytable values (1,'Che YYYY')
insert into mytable values (1,'Mat')
insert into mytable values (1,'Phy XXXX')

--Replace space in your column with a special character and remove it in your select statement
UPDATE mytable
SET unit=REPLACE(unit,' ','')

SELECT PersonID, REPLACE(Units,'', ' ') as Units
FROM (SELECT t1.PersonID,
Units =REPLACE( (SELECT Unit AS [data()]
FROM mytable t2
WHERE t2.PersonID = t1.PersonID
ORDER BY Unit
FOR XML PATH('')
), ' ', ',')
FROM mytable t1
GROUP BY PersonID)
t0 ;
drop table mytable