从下面的数据表开始,如何获取带有每个region
的键的返回JSON对象,并将其出现的总和作为值嵌套在region
的{{ 1}}?
示例表
country_code
预期结果
+---------------------+------------------+
| country_code | region |
+---------------------+------------------+
| 'CA' | 'Ontario' |
+---------------------+------------------+
| 'CA' | 'Ontario' |
+---------------------+------------------+
| 'CA' | 'Ontario' |
+---------------------+------------------+
| 'CA' | 'Quebec' |
+---------------------+------------------+
| 'CA' | 'Quebec' |
+---------------------+------------------+
| 'DE' | 'Bavaria' |
+---------------------+------------------+
| 'DE' | 'Bavaria' |
+---------------------+------------------+
| 'DE' | 'Bavaria' |
+---------------------+------------------+
| 'DE' | 'Bavaria' |
+---------------------+------------------+
| 'DE' | 'Saarland' |
+---------------------+------------------+
| 'DE' | 'Berlin' |
+---------------------+------------------+
| 'DE' | 'Berlin' |
+---------------------+------------------+
| 'JP' | 'Tokyo' |
+---------------------+------------------+
答案 0 :(得分:1)
又快又脏
with tbl(country_code,region)
as (values ('CA', 'Ontario')
,('CA', 'Ontario')
,('CA', 'Ontario')
,('CA', 'Quebec')
,('CA', 'Quebec')
,('DE', 'Bavaria')
,('DE', 'Bavaria')
,('DE', 'Bavaria')
,('DE', 'Saarland')
,('DE', 'Berlin')
,('DE', 'Berlin')
,('JP', 'Tokyo')
)
, groups as (select country_code,jsonb_build_object(region,count(*)) as x from tbl group by country_code,region)
, l1 as (select jsonb_build_object(country_code,jsonb_agg(x)) as y from groups group by country_code)
select jsonb_agg(y) from l1;
返回:
jsonb_agg |
----------------------------------------------------------------------------------------------------------------------------|
[{"CA": [{"Quebec": 2}, {"Ontario": 3}]}, {"JP": [{"Tokyo": 1}]}, {"DE": [{"Saarland": 1}, {"Berlin": 2}, {"Bavaria": 3}]}] |