![](/img/trans.png)
[英]Can I sum an array of jsonb in Postgresql with dynamic keys in a select statement?
[英]How can I calc sum for jsonb in PostgreSQL?
在CROSS JOIN
中使用jsonb_each_text
提取 json 記錄的每個元素,然后key
對values
進行匯總
SELECT j.key, sum(j.value::numeric)
FROM mytable
CROSS JOIN jsonb_each_text(data::jsonb) j (key,value)
GROUP BY j.key
演示: db<>fiddle
一種自然的方法是將總和放在一行中:
with my_table(data) as (
values
('{"BTC": "0.1"}'::jsonb),
('{"BTC": "0.2", "DOGE": "2.0"}'),
('{"BTC": "0.3"}')
)
select
sum((data->>'BTC')::numeric) as btc,
sum((data->>'DOGE')::numeric) as doge
from my_table;
btc | doge
-----+------
0.6 | 2.0
(1 row)
如果你堅持柱狀展示:
with my_table(data) as (
values
('{"BTC": "0.1"}'::jsonb),
('{"BTC": "0.2", "DOGE": "2.0"}'),
('{"BTC": "0.3"}')
)
select code, sum((data->>code)::numeric)
from my_table
cross join unnest(array['BTC', 'DOGE']) as code
group by code
order by code;
code | sum
------+-----
BTC | 0.6
DOGE | 2.0
(2 rows)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.