jam*_*uir 1 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 子句的情况下在行级别执行此聚合,如果可以,该语法可能是什么样子?
先感谢您。
即使您说您想避免,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 值。
| 归档时间: | 
 | 
| 查看次数: | 3052 次 | 
| 最近记录: |