Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用SQL执行JSON递归嵌套聚合_Sql_Json_Postgresql - Fatal编程技术网

如何使用SQL执行JSON递归嵌套聚合

如何使用SQL执行JSON递归嵌套聚合,sql,json,postgresql,Sql,Json,Postgresql,我有一些数据: 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 我想转换为嵌套形式的: rank_ | nested ---------------

我有一些数据:

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
我想转换为嵌套形式的:

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"}]}
其中“C”是子项,“D”是数据


到目前为止,我有以下代码,但到目前为止,我无法使其嵌套到任意深度:

Le'ts supose我们有带有数据的表
o

create table o (rank_ int, data varchar(10), parent_rank int) ;
insert into o (VALUES 
        (1, 'a', NULL),
        (2, 'b', 1),
        (3, 'c', 2),
        (4, 'd', 2),
        (5, 'e', NULL),
        (6, 'f', NULL),
        (7, 'g', 6),
        (8, 'h', 6)
    );
然后,您可以编写一个简单的递归函数,如:

CREATE FUNCTION C(r INT) RETURNS JSONB AS
  ' BEGIN
      return (             
            jsonb_build_object(
                ''D'', ( select 
                         o.data 
                         from o
                         where o.rank_=r), 
                ''C'', ( select 
                         coalesce(
                            array_to_json(array_agg( C(o.rank_)  
                                          ORDER BY o.rank_))::JSONB,
                            ''[]''::JSONB )
                         from o
                         where o.parent_rank=r)
               )
            );

    END
    '
  LANGUAGE plpgsql;
并调用根注释的函数:

SELECT o.rank_, c(o.rank_)
from o
where o.parent_rank is null
:

1   {"C":[{"C":[{"C":[],"D":"c"},{"C":[],"D":"d"}],"D":"b"}],"D":"a"}
5   {"C":[],"D":"e"}
6   {"C":[{"C":[],"D":"g"},{"C":[],"D":"h"}],"D":"f"}