I am trying to build a nested Json structure from a single table.
I am trying to get the final result to look like:
[
{
"contract_number":"GS00F0XXX",
'category': [
{
'cat_id': "874 1",
'socio': {
"eighta":false,
"sdvosb":false,
"edwosb":false
}
},
{
"cat_id":"874 6",
'socio': {
"eighta":false,
"sdvosb":false,
"edwosb":false,
}
}
]
},
{
'contract_number': "GS00Q14OAXXX",
'category': [
{
'cat_id': 'OASIS POOL1',
'socio': ...
}
]
}
]
The underlying table looks something like:
contract_type contract_number duns_number eighta sdvosb edwosb category
MOBIS GS00F0XXX 5555555 FALSE FALSE FALSE 874 1
MOBIS GS00F0XXX 5555555 FALSE FALSE FALSE 874 6
MOBIS GS00F0XXX 5555555 FALSE FALSE FALSE 874 7
OASIS GS00Q14OAXXX 5555555 FALSE FALSE FALSE OASIS POOL1
OASIS GS00Q14OAXXX 5555555 FALSE FALSE FALSE OASIS POOL2
I've tried this query, but it puts everything on two rows, and every time I try to nest a json_agg call I get an error about nestng aggregation functions.
select
json_build_object(
'contract_number', contract_number,
'info', json_agg(
json_build_object(
'category_id', category,
'eighta',eighta,
'sdvosb',sdvosb,
'edwosb',edwosb
)
)
)
from contract_vehicle
group by duns_number, contract_number
This results in SQL Error [42803]: ERROR: aggregate function calls cannot be nested
select
json_build_object(
'contract_number', contract_number,
'info', json_agg(
json_build_object(
'category_id', category,
'socio', jsonb_agg(
json_build_object(
'eighta',eighta,
'sdvosb',sdvosb,
'edwosb',edwosb
)
)
)
)
)
from contract_vehicle
group by duns_number, contract_number