Postgresql JSONB内联数组值的总和

时间:2017-04-29 14:49:43

标签: postgresql sum jsonb

我试图弄清楚对象数组中特定字段的内联求和的查询语法是什么。我的数据结构如下

CREATE TABLE "orders" (
  order_id int8,
  tax_lines jsonb
);
INSERT INTO "orders"(order_id, tax_lines) VALUES (4521745668, '[
  {
    "rate": 0.029,
    "price": "0.43",
    "title": "CO State Tax"
  },
  {
    "rate": 0.00985,
    "price": "0.15",
    "title": "Boulder County Tax"
  },
  {
    "rate": 0.0496,
    "price": "0.74",
    "title": "Boulder Municipal Tax"
  }
]');

我想要达到的结果是

order_id         cumulative_tax_rate
4521745668       .08845

这是我已经得到的

SELECT
  o.order_id,
  SUM((jsonb_array_elements(o.tax_lines) ->> 'rate')::numeric) AS cumulative_tax_rate
 FROM orders o WHERE o.order_id = '4521745668'

但它一直在要求我想避免的GROUP BY子句。我想知道是否有可能在行级别执行此聚合而没有group by子句,如果是这样,那么语法可能是什么样的?

提前谢谢。

2 个答案:

答案 0 :(得分:2)

即使您说要避免使用group by,我也会提供解决方案,因为这是您确实需要的。

select order_id, 
       sum(tax) tax
  from (SELECT o.order_id, 
               (jsonb_array_elements(o.tax_lines)->>'rate')::numeric tax
          FROM orders o) a
 where order_id = 4521745668 -- this you add if you want a specific order id
  group by order_id;         -- without it you will have all orders tax sum

这将为您提供所需的结果:

  order_id      tax
 4521745668   0.08845

如果您只需要在外部查询中添加order_id的where子句。 where order_id = 4521745668不需要引号,因为它是int8值。

答案 1 :(得分:1)

我与窗口聚合,而不是聚在一起 - 是你在找什么?..

t=# with a as (
SELECT
  o.order_id,
 (jsonb_array_elements(o.tax_lines ) ->> 'rate')::float AS cumulative_tax_rate
  FROM orders o WHERE order_id = 4521745668
)
select
distinct order_id, sum(cumulative_tax_rate) over (partition by order_id)
from a;
  order_id  |   sum
------------+---------
 4521745668 | 0.08845
(1 row)