【问题标题】:Sum all of the items in a JSONB array field对 JSONB 数组字段中的所有项目求和
【发布时间】:2017-01-09 19:55:19
【问题描述】:

如果我的表设置如下:

indicators:
  id: 56789,
  funding (JSONB): [
    {
      amount: 345678
    },
    {
      amount: 7899
    }
  ]

我可以成功地将每条记录的第一笔金额与:

Rails — Indicator.sum("(funding->0->>'amount')::float")

SQL — SELECT SUM((funding->0->>'amount')::float) FROM "indicators"

如何查询所有 amounts 的总和(不仅仅是 0 索引项)?

运行 Rails 5 和 Postgres 9.5.4。

注意:这篇文章类似于How do I query using fields inside the new PostgreSQL JSON datatype? - 但我正在寻找一种方法来迭代每个数组元素以对它们求和(而不是通过索引直接调用它们号)。

更新... 感谢@klin 在下面的回答,我能够将 Rails 版本放在一起,给我提供了总计:

Indicator.joins("cross join lateral jsonb_array_elements(funding)").sum("(value->>'amount')::float")

【问题讨论】:

    标签: sql ruby-on-rails json postgresql jsonb


    【解决方案1】:

    使用jsonb_array_elements()

    select sum((value->>'amount')::float)
    from indicators
    cross join lateral jsonb_array_elements(funding)
    

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 2016-05-09
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多