We have data as below:
We need output like this:
Solution:
For SQL server
STUFF function is the key here:
SELECT Id,STUFF( ( SELECT distinct ' ' + cast(Name as varchar(500)) from table1 t2 where t1.Id = t2.Id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,2,’ ‘ ) New_Name from table1 t1 group by Id,Name
MySql: In case of the MySQLGROUP_CONCAT function is used. Also, we can give the desired delimiter using SEPARATOR keyword:
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') as New_Name FROM test GROUP BY id;