简体   繁体   中英

SQL Server 2014 equivalent to GROUP_CONCAT()

I'm using SQL Server 2014. I have a country table and city table

Country Table

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

City Table

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

For some reason, we have a table that links country ID with different city ID as below

CountryCity table

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

Now what I want is using table CountryCity

I want to group all the cities to its country in one row or multiple column as below

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

I want to use the mapping in CountryCity and get the codes from country & city table

I tried below but still it's returning it in different rows

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

I think you are getting confused because there is an extraneous countryId in the city table. Just ignore it.

If you want one row per country, then don't do a join in the outer query. Do the join in the inner query:

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;

Your sample data does not have any statusid columns, so I removed that logic. You can include that logic in the appropriate place depending on the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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