Last active
July 22, 2021 21:31
-
-
Save bchapuis/2cc830002d389123f6fa2876d8571d72 to your computer and use it in GitHub Desktop.
Demonstrates how to extract and aggregate attributes in a json data structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT id, | |
array_to_json(array_remove(array_agg(a), NULL)) as a, | |
array_to_json(array_remove(array_agg(b), NULL)) as b, | |
array_to_json(array_remove(array_agg(c), NULL)) as c | |
FROM ( | |
SELECT jsonb_path_query_first(value, '$[*].id') as id, | |
jsonb_path_query(value, '$[*].a') as a, | |
jsonb_path_query(value, '$[*].b') as b, | |
jsonb_path_query(value, '$[*].c') as c | |
FROM ( | |
SELECT jsonb_array_elements('[ | |
[ | |
{ | |
"id": "1" | |
}, | |
{ | |
"a": "a" | |
}, | |
{ | |
"b": "b" | |
}, | |
{ | |
"a": "a" | |
}, | |
{ | |
"b": "b" | |
}, | |
{ | |
"c": "c" | |
} | |
], | |
[ | |
{ | |
"id": "2" | |
}, | |
{ | |
"a": "a" | |
}, | |
{ | |
"b": "b" | |
}, | |
{ | |
"a": "a" | |
}, | |
{ | |
"b": "b" | |
}, | |
{ | |
"b": "b" | |
} | |
] | |
]'::jsonb) as value | |
) AS objects | |
) AS objects | |
GROUP BY id; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment