如何根据PieCloudDB中的值聚合json列

问题描述 投票:0回答:1

在我的 PieCloudDB 数据库中,我有一个像这样的 json 列:

json_col
{“id”:1,“数据”:[{“col1”:“A”,“col2”:“B”,“col3”:“C”},{“col1”:“D”,“col2” ": "E","col3": "F"}]}
'{"id": 2,"data": [{"col1": "G","col2": "H","col3": "I"}, {"col1": "J"," col2": "K","col3": "L"}]}

我想以表格形式输出它,其中

id
colx
作为列。

我尝试了以下方法:

SELECT
    json_col->>'id' AS id,
    json_data.col1,
    json_data.col2,
    json_data.col3
FROM
    c,
    json_to_recordset(json_col->'data') AS json_data
    (
        col1 text,
        col2 text,
        col3 text
    )

得到了这个:

id col1 col2 col3
1 A B C
1 D E F
2 G H
2 J K L

但我想得到这样的结果,按 id 分组:

id col1 col2 col3
1 A、D B、E C,F
2 G,J H,K 我,L
json database
1个回答
0
投票

我找到了解决方案(在PieCloudDB数据库中使用

string_agg
):

SELECT
    json_col->>'id' AS id,
    string_agg((json_data->>'col1'), ',') AS col1,
    string_agg((json_data->>'col2'), ',') AS col2,
    string_agg((json_data->>'col3'), ',') AS col3
FROM
    c,
    json_array_elements(json_col->'data') AS json_data
GROUP BY
    id
ORDER BY
    id;
© www.soinside.com 2019 - 2024. All rights reserved.