0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.