1

Suppose I had rows like

id group1 group2 value
5 1 2 55
5 1 3 66
5 2 1 66
4 1 3 77

I'm looking to group on id so I'd have two rows with

| id       | json         
| -------- | -------------
| 5        | {1: {2: 55, 3: 66}, 2: {1: 66}}        
| 4        | {1: {3: 77}}            

I've tried combinations of JSON_OBJECT_AGG wrapped in JSON_BUILD_OBJECT with the results going to JSON_AGG. That is almost giving me what I want. The items are in an array. Each object in the array has only one outer key and all the inner keys are as expected. If I could combine all the objects in the array or just build the objects correctly, either way would solve the issue.

1 Answer 1

1

You need to use jsonb_object_agg() twice, first aggregating by id, group1 and then grouping only by id:

select id, jsonb_object_agg(group1, json) as json
from (
    select 
        id,
        group1,
        jsonb_object_agg(group2, value) as json
    from my_table
    group by id, group1
    ) s
group by id

Test it in db<>fidlle.

Sign up to request clarification or add additional context in comments.

1 Comment

You are my hero. Thank you!

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.