繁体   English   中英

SQL 服务器 2014 相当于 GROUP_CONCAT()

[英]SQL Server 2014 equivalent to GROUP_CONCAT()

我正在使用 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

我认为您会感到困惑,因为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列,因此我删除了该逻辑。 您可以根据表格将该逻辑包含在适当的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM