Convert multiple rows into one with comma as separator

Pavel Bastov picture Pavel Bastov · May 20, 2009 · Viewed 340.6k times · Source

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?

Answer

Hogan picture Hogan · Nov 23, 2009
 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