Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Concatenate & group multiple rows into a single row [duplicate]

I'm looking for a way to group whilst also concatenating rows into a comma separated string. Example:

Name            Place
Steve Jones     New York
Steve Jones     Washington
Albert Smith    Miami
Albert Smith    Denver

to ...

Steve Jones    New York, Washington
Albert Smith   Miami, Denver

Greatly appreciated

like image 974
BigIWT Avatar asked Oct 19 '25 21:10

BigIWT


1 Answers

If you use SQL Server 2008 and above, you can use STUFF and XML PATH to get the result you want.

SELECT DISTINCT Name
    , STUFF((
        SELECT ',' + Place
        FROM YourTable t1
        where t1.Name = t2.Name
        FOR XML PATH('')
    ), 1, 1, '') AS Places
FROM YourTable t2
like image 126
Eric Avatar answered Oct 21 '25 12:10

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!