Q:

How can I concatinate a subquery result field into the parent query? 

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? 

A:

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

A:

Try the solution to this question:
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?  
:)

