排序sql查询结果并连接

时间:2017-05-22 05:30:36

标签: sql sql-server

我有三个表国家,州和城市

enter image description here

我需要格式为

的结果
  

国家 | *所有州都属于由','分隔的国家/地区。 * | 所有城市   属于以','

分隔的国家/地区

州也不应该有任何重复。 例如:

  

巴达赫,巴达赫,巴达赫,巴达赫,巴达赫,Badgis,Badgis

不应该发生。

我写了一个查询来获取列表

 with aggregatelist(countryname,statename,cityname) as 
 ( select c.name as countryname,s.name as statename,ct.name as cityname from countrymaster c inner join statemaster s  on 
  c.id=s.countryid inner join citymaster ct on ct.stateid=s.id group by c.name,s.name,ct.name
  )

但这不会返回所需的格式。

如果没有临时表,我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

使用StuffFOR XML路径来刺激group concat

SELECT co.[Name], 
    STUFF(
    (
    SELECT ',' + st.[Name]
    FROM State st 
    WHERE co.Id = st.CountryId
    FOR XML PATH('')
    ), 1, 1, '') As States,
    STUFF(
    (
    SELECT ',' + ci.[Name]
    FROM State st 
    INNER JOIN City ci ON st.Id = ci.StateId
    WHERE co.Id = st.CountryId
    FOR XML PATH('')
    ), 1, 1, '') As cities
FROM Country co

答案 1 :(得分:2)

如果您有3个表,如下所示,则SQL应如下所示:

create table city ( id number, name varchar2(1000),state number);
create table state ( id number, name varchar2(1000),country number);
create table ctry ( id number, name varchar2(1000),cc varchar2(10));

then SQL should look like:

SELECT a.name
      ,a.states
      ,b.cities
  FROM (SELECT c.id
              ,c.name
              ,listagg(s.name, ',') within GROUP(ORDER BY s.id) states
          FROM state s
          JOIN ctry c
            ON s.country = c.id
         GROUP BY c.id, c.name) a
 RIGHT JOIN (SELECT s.name
                   ,s.country
                   ,listagg(c.name, ',') within GROUP(ORDER BY c.id) cities
               FROM state s
               JOIN city c
                 ON s.id = c.state
              GROUP BY s.name
                      ,s.country) b
    ON a.id = b.country