对 JSONB 数组字段中的所有项目求和
Sum all of the items in a JSONB array field
如果我的 table 设置如下:
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.
注意: 这个 post 类似于 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")
select sum((value->>'amount')::float)
from indicators
cross join lateral jsonb_array_elements(funding)
如果我的 table 设置如下:
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.
注意: 这个 post 类似于 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")
select sum((value->>'amount')::float)
from indicators
cross join lateral jsonb_array_elements(funding)