Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multiple rows into one with comma as separator [duplicate]

Tags:

tsql

csv

rows

If I issue SELECT username FROM Users I get this result:

 username -------- Paul John Mary 

but what I really need is one row with all the values separated by comma, like this:

 Paul, John, Mary 

How do I do this?

like image 580
Pavel Bastov Avatar asked May 20 '09 12:05

Pavel Bastov


People also ask

How do I merge multiple SQL rows with distinct values shown as comma separated?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


1 Answers

 select    distinct       stuff((         select ',' + u.username         from users u         where u.username = username         order by u.username         for xml path('')     ),1,1,'') as userlist from users group by username 

had a typo before, the above works

like image 190
Hogan Avatar answered Sep 20 '22 13:09

Hogan