If my table is setup like:
funding (JSONB): [
I can successfully sum the first amounts on every record with:
How would you query a sum of all of the
SELECT SUM((funding->0->>'amount')::float) FROM "indicators"
(not just the 0 index items)?
Running Rails 5 & Postgres 9.5.4.
This post is similar to How do I query using fields inside the new PostgreSQL JSON datatype?
- but I'm looking for a way to iterate over each of the array elements to sum them (as opposed to calling them directly by an index number).
Thanks to @klin's answer below, I was able to put together the Rails version that gave me the aggregate total:
Indicator.joins("cross join lateral jsonb_array_elements(funding)").sum("(value->>'amount')::float")