How to get SUM values ​​in a JSONB column

I have 1-dimensional JSONB on postgresql like this:

SELECT '{"a": 1, "b": 2, "c": 3}'::jsonb;

How to get SUM values ​​in a JSONB column? How is the sum of 1 + 2 + 3?

PostgreSQL has a jsonb_object_keys function , but I was looking for something like "jsonb_object_values" (I know this function does not exist)

# select jsonb_object_keys( '{"a": 1, "b": 2, "c": 3}'::jsonb );
 jsonb_object_keys 
-------------------
 a
 b
 c
(3 rows)
+4
source share
1 answer

The function jsonb_each_text()extends the set of JSON objects into strings in the format (key, value). Since it returns a rowset, you should use it as a row source. Since it returns data in a format text, you must pass it to the appropriate type before further processing.

SELECT sum(v::integer)
FROM jsonb_each_text('{"a": 1, "b": 2, "c": 3}'::jsonb) j(k,v);
+3
source

Source: https://habr.com/ru/post/1652194/


All Articles