This is my data
with _temp_data as
(
select
unnest(ARRAY['A','B','A','A']) as hobbies_1
,unnest(ARRAY['E','F','A','F']) as hobbies_2
)
select * from _temp_data
Input data:
hobbies_1|hobbies_2|
---------+---------+
A |E |
B |F |
A |A |
A |F |
I want to transform this table into single row combination like this
hobbies_1 | hobbies_2
{'A':3,'B':1} |{'E':1,'F':2,'F':1}
2
Answers
With the help of jsonb_object_agg you can do achive this using below query,
The inner subqueries only select and group by the respective columns (hobbies_1 and hobbies_2) they are concerned with and then outer queries perform the aggregation and cross join
You can do this in a single scan of the base table, by using
GROUPING SETS
and conditional aggregation.db<>fiddle