简体   繁体   English

如何在postgres中对jsonb值求和?

[英]how to sum jsonb values in postgres?

I'm working with postgres and I need to sum the value of jsonb fields我正在使用 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                │

So I need to sum all the values for the total field for all the records and after that I need to use aggregate functions on them like min, max and avg所以我需要对所有记录的 total 字段的所有值求和,然后我需要对它们使用聚合函数,如 min、max 和 avg

I started a query like this我开始了这样的查询

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;

I'm confused after this.这之后我很困惑。 Is there a better way to solve this problem?有没有更好的方法来解决这个问题?

I need to use the aggregate function after adding all the values inside jsonb.在 jsonb 中添加所有值后,我需要使用聚合函数。 Is that possible?那可能吗?

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 }

I was expecting this我期待这个

 id   json_object_agg
   25    3
   26    3

Something like this像这样的东西

To sum all the values of the total column for each of the rows, you need to group by id but not by key :要对每一行的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

To calculate the min, max, avg on all the rows of the table, you don't need to group the rows :要计算表的所有行的 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