6

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?

Anonymoose
  • 5,662
  • 4
  • 33
  • 41
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

3 Answers3

8

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

patrick.elmquist
  • 2,113
  • 2
  • 21
  • 35
Greg Smith
  • 111
  • 1
  • 4
3

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?

:)

Community
  • 1
  • 1
Jeremy Smyth
  • 23,270
  • 2
  • 52
  • 65
  • Ha -> that post was also using cars as an example :) I ended up creating a temp UDF, run my code, drop udf. Works great :) This is for an import process .. hence the create/drop of the udf. cheers :) – Pure.Krome Jun 19 '09 at 08:01
1

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
Mohamed hesham
  • 130
  • 1
  • 12