简体   繁体   English

Postgresql 合并/聚合 json 列并返回 json 对象作为输出

[英]Postgresql merge/aggregate json column and return json object as output

I am using Postgresql 9.6我正在使用 Postgresql 9.6

I have a table, where my column is of type json.我有一张表,其中我的列是 json 类型。

create table test (
my_data json,
.
.
);

When queried, for each row the column is shown as json:查询时,对于每一行,列显示为 json:

样本数据

I want to aggregate the data, for sake of simplicity selected 2 columns only.我想聚合数据,为了简单起见,只选择了 2 列。 I need to group by col1_data.我需要按 col1_data 分组。 I want like below:我想要如下:

预期结果

I tried to use json_agg, but that will agregate and output as array of jsons.我尝试使用 json_agg,但这会聚合并输出为 jsons 数组。

select col1_data, json_agg(col2_data) as col2_data
from test
group by col1_data;

错误的输出

Can someone help to convert the array of json to json?有人可以帮助将json数组转换为json吗?

This should do it:这应该这样做:

select col1_data, json_agg(col2_element) as col2_data
from test, json_array_elements(col2_data) as col2_element
group by col1_data;

Alternatively, you can write your own aggregate function that concatenates json arrays.或者,您可以编写自己的聚合函数来连接 json 数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM