PostgreSQL 聚合 json 个数组
PostgreSQL aggregate over json arrays
我看到很多关于使用 json_array_elements 提取 JSON 数组元素的参考资料。但是,这似乎只适用于 1 个阵列。如果我在通用查询中使用它,我会得到错误
ERROR: cannot call json_array_elements on a scalar
给出这样的东西:
orders
{ "order_id":"2", "items": [{"name": "apple","price": 1.10}]}
{ "order_id": "3","items": [{"name": "apple","price": 1.10},{"name": "banana","price": 0.99}]}
我要提取
item
count
apple
2
banana
1
或
item
total_value_sold
apple
2.20
banana
0.99
是否可以使用 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;
我看到很多关于使用 json_array_elements 提取 JSON 数组元素的参考资料。但是,这似乎只适用于 1 个阵列。如果我在通用查询中使用它,我会得到错误
ERROR: cannot call json_array_elements on a scalar
给出这样的东西:
orders |
---|
{ "order_id":"2", "items": [{"name": "apple","price": 1.10}]} |
{ "order_id": "3","items": [{"name": "apple","price": 1.10},{"name": "banana","price": 0.99}]} |
我要提取
item | count |
---|---|
apple | 2 |
banana | 1 |
或
item | total_value_sold |
---|---|
apple | 2.20 |
banana | 0.99 |
是否可以使用 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;