Postgres 创建 JSON 行值计数

Postgres Create JSON Count of Row Value

我正在尝试创建一个视图,其中聚合数据显示为 json 对象:

 thing_named_not_unique | emergency_code 
------------------------+----------------
foo                     |  1
foo                     |  2
foo                     |  1
bar                     |  1
bar                     |  2

让结果成为

 thing_named_not_unique | emergency_code_counts 
------------------------+----------------
foo                     |  {'1': 2, '2': 1}
bar                     |  {'1': 1, '2': 1}

我对 Postgres JSON 函数还很陌生,不知道如何为此构建聚合。

您需要聚合两次。第一个聚合是计算每个“事物”的紧急代码计数。第二个聚合然后聚合每个事物的计数:

select thing_named_not_unique, jsonb_object_agg(emergency_code, cnt) as emergency_code_counts
from (
  select thing_named_not_unique, emergency_code, count(*) as cnt
  from the_table
  group by thing_named_not_unique, emergency_code
) t
group by thing_named_not_unique
order by thing_named_not_unique