Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 626
Pure.Krome Avatar asked Mar 01 '23 14:03

Pure.Krome


1 Answers

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://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

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

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

like image 189
Greg Smith Avatar answered Mar 03 '23 04:03

Greg Smith