0

We have a PostgreSQL jsonb column containing hashes which in turn contain arrays of values:

id | hashes
---------------
1  | {"sources"=>["a","b","c"], "ids"=>[1,2,3]}
2  | {"sources"=>["b","c","d","e","e"], "ids"=>[1,2,3]}

What we'd like to do is create a jsonb query which would return

code | count
---------------
"a"  | 1
"b"  | 2
"c"  | 2
"d"  | 1
"e"  | 2

we've been trying something along the lines of

SELECT jsonb_to_recordset(hashes->>'sources') 

but that's not working - any help with this hugely appreciated...

3 Answers 3

1

The setup (should be a part of the question, note the proper json syntax):

create table a_table (id int, hashes jsonb);
insert into a_table values
(1, '{"sources":["a","b","c"], "ids":[1,2,3]}'),
(2, '{"sources":["b","c","d","e","e"], "ids":[1,2,3]}');

Use the function jsonb_array_elements():

select code, count(code)
from
    a_table,
    jsonb_array_elements(hashes->'sources') sources(code)
group by 1
order by 1;

 code | count 
------+-------
 "a"  |     1
 "b"  |     2
 "c"  |     2
 "d"  |     1
 "e"  |     2
(5 rows)    
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT h, count(*)
FROM (
    SELECT jsonb_array_elements_text(hashes->'sources') AS h FROM mytable
  ) sub
GROUP BY h
ORDER BY h;

Comments

0

We finally got this working this way:

SELECT jsonb_array_elements_text(hashes->'sources') as s1,
count(jsonb_array_elements_text(hashes->'sources'))
FROM a_table
GROUP BY s1;

but Klin's solution is more complete and both Klin and Patrick got there quicker than us (thank you both) - so points go to them.

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.