复杂 JSON B 聚合与 GROUP BY
Complex JSON B aggregation with GROUP BY
我有一个table像这样的东西
STUDENT JSONB Column
1 {"total":8,"healthy": 2,"unhealthy":5,"X":7}
1 {"total":12,"healthy": 4"unhealthy":3,"X":9}
2 {"total":3,"healthy": 4}
2 {"total":4,"healthy": 1}
预计
1 {"total":20,"healthy": 6,"unhealthy":8,"X":16}
2 {"total":7,"healthy": 5}
我想对 JSON 内的值进行分组和求和。我尝试使用 JSONB_OBJ_AGG
我知道如何让它与硬编码一起工作。但我的问题是键数可以是 6-9。我无法在 SQL.
中对键进行硬编码
您可以像这样使用 jsonb_object_agg
函数来获取所有键的总和而无需声明它们:
select id, jsonb_object_agg(key, sum) from
(
select id, key, sum(value::int)
from my_table
cross join jsonb_each_text(content)
group by id, key
) tmp_each group by id
演示在 DBfiddle
我有一个table像这样的东西
STUDENT JSONB Column
1 {"total":8,"healthy": 2,"unhealthy":5,"X":7}
1 {"total":12,"healthy": 4"unhealthy":3,"X":9}
2 {"total":3,"healthy": 4}
2 {"total":4,"healthy": 1}
预计
1 {"total":20,"healthy": 6,"unhealthy":8,"X":16}
2 {"total":7,"healthy": 5}
我想对 JSON 内的值进行分组和求和。我尝试使用 JSONB_OBJ_AGG 我知道如何让它与硬编码一起工作。但我的问题是键数可以是 6-9。我无法在 SQL.
中对键进行硬编码您可以像这样使用 jsonb_object_agg
函数来获取所有键的总和而无需声明它们:
select id, jsonb_object_agg(key, sum) from
(
select id, key, sum(value::int)
from my_table
cross join jsonb_each_text(content)
group by id, key
) tmp_each group by id
演示在 DBfiddle