使用jsonb_build_object返回带有动态键和聚合值的对象

时间:2018-10-25 16:10:25

标签: sql json postgresql

从下面的数据表开始,如何获取带有每个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'      |
+---------------------+------------------+

1 个答案:

答案 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}]}] |