如何将子查询结果字段连接到父查询?

时间:2009-06-19 07:27:42

标签: sql-server sql-server-2008 subquery concatenation

DB:Sql Server 2008。

我有一个非常(假的)groovy查询,如下所示: -

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

这就是我想要的......

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

所以,我尝试使用

AS [Text()] ... FOR XML PATH('')但是包含了奇怪的编码字符(例如回车)。 ......所以我对此并不百分之百。

我还试图查看是否有COALESCE解决方案,但我的所有尝试都失败了。

那么 - 有什么建议吗?

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

回答了一个旧帖子,只是认为它需要更新SQL Server的新版本:

对于SQL Server 2017,请使用STRING_AGG(表达式分隔符

GROUP_CONCAT是MySQL。

在SQL 2017之前,您还可以执行以下操作(从我们当前基于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

链接到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

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

,最后链接到FOR XML: https://docs.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-2017

答案 2 :(得分:0)

使用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