我看到很多关于使用 json_array_elements 提取 JSON 数组元素的引用资料。但是,这似乎只适用于 1 个数组。如果我在一般查询中使用它,我会得到错误
ERROR: cannot call json_array_elements on a scalar
给定这样的东西:
我要提取
或者
是否可以使用 json_array_elements 像这样聚合 json 数组?
最佳答案
使用orders->'items'
的函数来展平数据:
select elem->>'name' as name, (elem->>'price')::numeric as price
from my_table
cross join jsonb_array_elements(orders->'items') as elem;
很容易从扁平化的数据中得到你想要的聚合:
select name, count(*), sum(price) as total_value_sold
from (
select elem->>'name' as name, (elem->>'price')::numeric as price
from my_table
cross join jsonb_array_elements(orders->'items') as elem
) s
group by name;
关于arrays - PostgreSQL 聚合 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70795053/