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?
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 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.