Pregunta

DB: SQL Server 2008.

Tengo una consulta maravillosa (falsa) como esta: -

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

Y esto es lo que intento obtener ...

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

Entonces, intenté usar

AS [Text ()] ... FOR XML PATH ('') pero eso incluía caracteres codificados extraños (por ejemplo, retorno de carro). ... así que no estoy 100% contento con eso.

También intenté ver si hay una solución COALESCE, pero todos mis intentos fallaron.

Entonces, ¿alguna sugerencia?

Otros consejos

Respondiendo a una publicación anterior, pensé que necesitaba una actualización para las versiones más nuevas de SQL Server:

Para SQL Server 2017 use STRING_AGG ( expresión , separador )

GROUP_CONCAT es MySQL.

Antes de SQL 2017, también puede hacer algo como (recortado de nuestra base de código actual en 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

Enlaces a 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

Enlace a COSAS: https: //docs.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-2017

y finalmente enlaces a 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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top