繁体   English   中英

同一表中的SQL嵌套组

[英]SQL Nested Group within the Same Table

我的数据看起来像这样:

id      key         value
--------------------------------
1       country     us
1       state       nj
1       city        trenton
2       country     us
2       state       nj
2       city        springfield
3       country     us
3       state       nj
3       city        belmar
4       country     us
4       state       ny
4       city        new york
4       country     us
4       state       ny
4       city        white plains
4       country     canada
4       state       ontario
4       city        toronto
5       country     us
5       state       nj
5       city        trenton

我正在尝试编写一个SQL查询以按唯一的国家,州,城市进行分组

country     state       city
--------------------------------------
us          nj          trenton
us          nj          springfield
us          nj          belmar
us          ny          new york
us          ny          white plains
canada      ontario     toronto

我可以获取DISTINCT的国家/地区,州和城市,但不确定如何将它们与ID列一起加入。

值得指出的是,这是一个数据混乱,并乞求“规范化”。 话虽如此,您可以尝试:

    SELECT cn.value as country, st.value as state, ct.value as city
    FROM table cn
    LEFT JOIN table st ON cn.id = st.id
    LEFT JOIN table st ON cn.id = ct.id
    WHERE cn.key = 'country'
    AND st.key = 'state'
    AND ct.key = 'city'
    ORDER BY cn.value , st.value , ct.value 

您可以为此使用条件聚合:

select t.id,
       max(case when t.key = 'country' then t.value end) as country,
       max(case when t.key = 'state' then t.value end) as state,
       max(case when t.key = 'city' then t.value end) as city
from t
group by id;

即使没有填充所有三个值,这也具有保留所有id的优点。

暂无
暂无

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

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