Question

DB: Sql Server 2008.

I have a really (fake) groovy query like this:-

SELECT CarId, NumberPlate
    (SELECT Owner
     FROM Owners b
     WHERE b.CarId = a.CarId) AS Owners
FROM Cars a
ORDER BY NumberPlate

And this is what I'm trying to get...

=> 1    ABC123     John, Jill, Jane
=> 2    XYZ123     Fred
=> 3    SOHOT      Jon Skeet, ScottGu

So, i tried using

AS [Text()] ... FOR XML PATH('') but that was inlcuding weird encoded characters (eg. carriage return). ... so i'm not 100% happy with that.

I also tried to see if there's a COALESCE solution, but all my attempts failed.

So - any suggestions?

Was it helpful?

OTHER TIPS

Answering an old post, just thought it needed an update for newer versions of SQL Server:

For SQL Server 2017 use STRING_AGG(expression, seperator)

GROUP_CONCAT is MySQL.

Prior to SQL 2017, you can also do something like (snipped from our current code base on SQL Server 2016):

SELECT CarId, NumberPlate,
    (STUFF(( SELECT ', ' + b.Owner
        FROM Owners b
        WHERE b.CarId = a.CarId
        FOR XML PATH('')
        )
        ,1,2,'') AS Owners
FROM Cars a
ORDER BY NumberPlate

Links to STRING_AGG https://database.guide/the-sql-server-equivalent-to-group_concat/ https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

Link to STUFF: https://docs.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-2017

and finally links to FOR XML: https://docs.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-2017

Use GROUP_CONCAT

SELECT CarId, NumberPlate
    (SELECT GROUP_CONCAT(Owner)
     FROM Owners b
     WHERE b.CarId = a.CarId) AS Owners
    FROM Cars a
ORDER BY NumberPlate
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top