PostgreSQL JSONB |嵌套数组可导致无法嵌套ERROR聚合函数调用

时间:2019-08-16 07:26:37

标签: node.js postgresql aggregate-functions psql pg

所以我正在尝试对多个查询进行卷积,并将结果形成为

[

    {
        heading: 'Test',
        subheading: 'SubTest',
        pItems: [
            {
                pid: 1,
                product_name: 'Random Product',
                stock: 500
            },
            {
                pid: 1,
                product_name: 'Random Product',
                stock: 500
            }
        ]
    },
    {
        heading: 'Test 2',
        subheading: 'SubTest 2',
        pItems: [
            {
                pid: 1,
                product_name: 'Random Product 2',
                stock: 500
            },
            {
                pid: 1,
                product_name: 'Random Product 2',
                stock: 500
            }
        ]
    }

]

这是我尝试过的

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=af81919b853b571ca2f25c96abbad596

但是我遇到了这个错误

  

错误:聚合函数调用无法嵌套

1 个答案:

答案 0 :(得分:1)

您有两个json_agg()通话。此函数是一个汇总函数。对于每个嵌套的聚合,您需要一个单独的GROUP BY子句。这就是错误消息的内容:

demo:db<>fiddle

SELECT 
    *
FROM (
    SELECT 
        test, client_id, project_id,
        json_build_object (
            'myData_updated',
            json_agg(p_items)
        )
    FROM (
        SELECT
            test, client_id, project_id,
            jsonb_build_object(
                'heading', heading_elems -> 'heading',
                'subheading', heading_elems -> 'subheading',
                'pItems', json_agg(elems || jsonb_build_object('product_name', po.name))
            ) AS p_items

        FROM mainTable mt CROSS JOIN LATERAL
            jsonb_array_elements(mt.myData) AS heading_elems CROSS JOIN LATERAL
            jsonb_array_elements(heading_elems -> 'pItems') AS elems

        JOIN products po ON (elems ->> 'pid' )::int = po.pid

        GROUP BY test, client_id, project_id, heading_elems
    ) s
    GROUP BY test, client_id, project_id
) s

INNER JOIN clients client ON client.client_id = s.client_id
INNER JOIN projects project on project.project_id = s.project_id

此外,在您的情况下,我将避免混淆JSON部分并加入所有其他表。这就是为什么我将JSON部分放入子查询并最后加入不相关的表的原因。