【问题标题】:SQL Server 2014 equivalent to GROUP_CONCAT()SQL Server 2014 相当于 GROUP_CONCAT()
【发布时间】:2021-05-05 10:29:32
【问题描述】:

我使用的是 SQL Server 2014。我有一个 country 表和 city

国家/地区表

   ID | Code
   ---+-------
   1  |  USA
   2  |  UK
   

城市表

   ID | Code  | CountryID
  ----+-------+------------
   1  |  JSN  |    1
   2  |  REH  |    2

出于某种原因,我们有一个表将国家 ID 与不同的城市 ID 联系起来,如下所示

CountryCity

CountryID | CityID
----------+-------
    1     |   2
    1     |   4
    2     |   3
    1     |   5
    2     |   6

现在我想要的是使用表CountryCity

我想将所有城市分组到其国家/地区的一行或多列中,如下所示

CountryID | CountryCode | CitiesCode
----------+-------------+-----------
    1           USA        JSN , NYC 

我想使用CountryCity 中的映射并从countrycity 表中获取代码

我在下面尝试过,但它仍然在不同的行中返回它

select
    cc.countryID,
    cc.countryCode,
    citiedCode = stuff((select ',' + c.code
                        from dbo.city c
                        where cc.cityID = c.id
                        for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '')
from 
    dbo.[CountryCity] cc
inner join 
    country on country.id = cc.countryid 
where 
    cc.statusid = 1 and country.statusid = 1

【问题讨论】:

  • 请标注sql server的版本
  • 我认为您应该在子查询中使用countryID。假设city 表的每一行都有对应的countryID,类似于cc.CountryID = c.CountryID
  • STRING_AGG 是在 SQL Server 2017 中添加的。顺便说一下,仍在主流支持中的最旧的 SQL Server 版本是 SQL Server 2016。您为什么使用 SQL Server 2014?
  • 至于您当前的问题,您仍然需要在计算聚合之前对行进行分组。 XML 技术将通过将 子查询 的所有结果转换为带空的 XML 来聚合它们。标签名称,但 outer 查询仍然需要对数据进行分组
  • CountryCity 与您的FROM 中的Country 具有多对一关系。为什么您期望多行?如果你想聚合城市,CountryCity 也需要在你的聚合中。

标签: sql sql-server sql-server-2014 string-aggregation


【解决方案1】:

我认为您会感到困惑,因为city 表中有一个无关的countryId。无视就好。

如果您希望每个国家/地区有一行,则不要在外部查询中进行联接。在内部查询中进行连接:

select co.countryID, co.countryCode,
       stuff((select ',' + c.code
              from dbo.city c join
                   countrycity cc
                   on cc.cityid = c.id
              where cc.countryid =  co.id
              for xml path(''), type
             ).value('.', 'nvarchar(max)'), 1, 1, ''
            ) as citiedCode
from country co;

您的示例数据没有任何 statusid 列,因此我删除了该逻辑。您可以根据表格将该逻辑包含在适当的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 2013-10-07
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多