I have some data:
rank_ | data | parent_rank
--------------------------
1 | a | NULL
2 | b | 1
3 | c | 2
4 | d | 2
5 | e | NULL
6 | f | NULL
7 | g | 6
8 | h | 6
that I'd like to transform to nested form:
rank_ | nested
--------------------------------------------------------------------------------------
1 | {"D": "a", "C": [{"C": [{"C": [], "D": "c"}, {"C": [], "D": "d"}], "D": "b"}]}
5 | {"D": "e", "C": []}
6 | {"D": "f", "C": [{"C": [], "D": "g"}, {"C": [], "D": "h"}]}
where "C" is children and "D" is data.
So far I have the following code, but I've been so far unable to make it nest to arbitrary depth: https://www.db-fiddle.com/f/g7RFZQRX5JrzaYPXs62BNe/0