Quinma
Quinma

Reputation: 1476

Can I sum an array of jsonb in Postgresql with dynamic keys in a select statement?

I have a jsonb object in postgres:

[{"a": 1, "b":5}, {"a":2, "c":3}]

I would like to get an aggregate sum per unique key:

{"a":3, "b":5, "c":3}

The keys are unpredictable.

Is it possible to do this in Postgres with a select statement?

Upvotes: 0

Views: 297

Answers (1)

404
404

Reputation: 8572

Query:

SELECT key, SUM(value::INTEGER)
FROM (
  SELECT (JSONB_EACH_TEXT(j)).*
  FROM JSONB_ARRAY_ELEMENTS('[{"a": 1, "b":5}, {"a":2, "c":3}]') j
) j
GROUP BY key
ORDER BY key;

Results:

| key | sum |
| --- | --- |
| a   | 3   |
| b   | 5   |
| c   | 3   |

DB Fiddle

Upvotes: 2

Related Questions