PostgreSQL避免嵌套聚合函数

时间:2017-09-08 15:39:49

标签: postgresql

    SELECT
        p.id AS id,
        json_agg((SELECT x FROM (SELECT 
            c.id, 
            c.name, 
            json_agg((SELECT y FROM (SELECT s.id, s.name) y)) AS js2
            ) x)) AS js1
    FROM p
    INNER JOIN s ON s.id = p.s_id
    INNER JOIN c ON c.s_id = p.s_id
    INNER JOIN cc ON c.id = cc.c_id AND p.c_id = cc.c_id
    GROUP BY p.c_id;

我想像这样聚合我的sql,但psql不允许我做js2。

  

错误:聚合函数调用不能嵌套json_agg((SELECT y FROM(SELECT s.id,...

我该如何避免这种情况?

1 个答案:

答案 0 :(得分:0)

尝试将js2中的json_agg更改为row_to_json

 SELECT
        p.id AS id,
        json_agg((SELECT x FROM (SELECT 
            c.id, 
            c.name, 
            row_to_json((SELECT y FROM (SELECT s.id, s.name) y)) AS js2
            ) x)) AS js1
    FROM p
    INNER JOIN s ON s.id = p.s_id
    INNER JOIN c ON c.s_id = p.s_id
    INNER JOIN cc ON c.id = cc.c_id AND p.c_id = cc.c_id
    GROUP BY p.c_id;

-HTH