我正在使用 postgres,我需要對 jsonb 欄位的值求和
Column │ Type │ Modifiers
─────────────────┼──────────────────────┼────────────────────────────────────────────────────────────────────
id │ integer │ not null default
practice_id │ character varying(6) │ not null
date │ date │ not null
pct_id │ character varying(3) │
astro_pu_items │ double precision │ not null
astro_pu_cost │ double precision │ not null
total │ jsonb │
所以我需要對所有記錄的 total 欄位的所有值求和,然后我需要對它們使用聚合函式,如 min、max 和 avg
我開始了這樣的查詢
select id, json_object_agg(key, val)
from (
select id, key, sum(value::numeric) val
from mytable t, jsonb_each_text(total)
group by id, key
) s
group by id;
這之后我很困惑。有沒有更好的方法來解決這個問題?
在 jsonb 中添加所有值后,我需要使用聚合函式。那可能嗎?
I'm getting a result like this
id json_object_agg
25 { "a" : 1, "b" : 2 }
26 { "a" : 1, "b" : 2 }
24 { "b" : 2, "a" : 1 }
我期待這個
id json_object_agg
25 3
26 3
像這樣的東西
uj5u.com熱心網友回復:
要total對每一行的列的所有值求和,您需要分組 byid但不是 by key:
select t.id, sum(tt.value::numeric) val
from mytable t, jsonb_each(total) AS tt
where jsonb_typeof(tt.value) = 'number' -- to avoid errors in the sum() if non numeric values
group by t.id
要計算表的所有行的 min、max、avg,您不需要對行進行分組:
select min(s.val), max(s.val), avg(s.val)
from
(
select t.id, sum(tt.value::numeric) val
from mytable t, jsonb_each(total) AS tt
where jsonb_typeof(tt.value) = 'number' -- to avoid errors in the sum() if non numeric values
group by t.id
) as s
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352993.html
標籤:sql PostgreSQL
上一篇:表中的行重復
