[英]SQL Nested Group within the Same Table
I have data that looks something like this: 我的数据看起来像这样:
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
I'm trying to write a SQL query to group by unique country, state, city 我正在尝试编写一个SQL查询以按唯一的国家,州,城市进行分组
country state city
--------------------------------------
us nj trenton
us nj springfield
us nj belmar
us ny new york
us ny white plains
canada ontario toronto
I'm able to get DISTINCT country, state, and city, but I'm not sure how to join them together with the ID column. 我可以获取DISTINCT的国家/地区,州和城市,但不确定如何将它们与ID列一起加入。
It's worth stating for the record that this is a data mess and begs for "normalization". 值得指出的是,这是一个数据混乱,并乞求“规范化”。 Having said that, you might try: 话虽如此,您可以尝试:
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
You can use conditional aggregation for this: 您可以为此使用条件聚合:
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;
This has the advantage of keeping all id
s, even when not all three values are populated. 即使没有填充所有三个值,这也具有保留所有id
的优点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.