1

I have a column of json arrays, and I need to produce counts of the values inside the arrays

so if my data looks like

["1", "2"]
["1", "2"]
["1", "2", "3"]
["1"]
["2"]
["2"]

I need to produce something like

{"1" => 4, "2" => 5, "3" => 1}

Is this kind of aggregation possible in Postgres? I'm honestly not sure where to start.

1 Answer 1

3

Use jsonb_array_elements() to turn the array into a SETOF (rows of output). Then just aggregate normally.

testdb=# with input_data as (select '["1", "1", "2"]'::jsonb j)
SELECT elem, count(elem)
FROM input_data, jsonb_array_elements(input_data.j) AS elem
GROUP BY 1
ORDER BY 1;
 elem | count 
------+-------
 "1"  |     2
 "2"  |     1
(2 rows)
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.