I have the table with hierarchical data. I want to aggregate the data from one table to a complex json. The elements should be grouped by section column. And nested json should be grouped by subsection column
----------------------------------------------
| id | section | subsection | subsubsection |
----------------------------------------------
| 111 | s_1 | null | null | // root section
----------------------------------------------
| 222 | s_1 | ss_2 | null | // root subsection
----------------------------------------------
| 333 | s_1 | ss_2 | sss_3 |
----------------------------------------------
| 444 | s_1 | ss_2 | sss_4 |
----------------------------------------------
| 555 | s_2 | null | null | // root section
----------------------------------------------
| 666 | s_2 | ss_3 | null | // root subsection
----------------------------------------------
I want to create json trees and save them as view
{
"id": 111,
"section": "s_1",
"subsections": [
{
"id": 222,
"subsection": "ss_2",
"subsections": [
{
"id": 333,
"subsection": "sss_3"
},
{
"id": 444,
"subsection": "sss_4"
}
]
}
]
}
What I tried to do:
create or replace view my_view(
name
) as
SELECT
(
SELECT
json_build_object(
'section', a.section,
'subsections', a.sections
)
FROM (SELECT b.section,
json_agg(
json_build_object(
'subsection', b.subsection,
'subsubsections', b.subsections
)
) AS sections
FROM (SELECT c.section,
c.subsection,
json_agg(
json_build_object(
'subsubsection', c.subsubsection
)
) AS subsections
FROM table AS c
GROUP BY section, subsection
) AS b
GROUP BY b.section) AS a
) AS name;
But in my solution I can't and an id to each tree node. How to add the each node id to result tree?