簡體   English   中英

如何在postgres中對jsonb值求和?

[英]how to sum jsonb values in postgres?

我正在使用 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

像這樣的東西

要對每一行的total列的所有值求和,您需要按id而不是按key分組:

select t.id, sum(tt.value::numeric) val
from mytable t, jsonb_each(total) AS tt
where jsonb_typeof(tt) = '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) = 'number'  -- to avoid errors in the sum() if non numeric values
    group by t.id
) as s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM