以下是样本数据
id | data_value
1 | [{"a":"f1"},{"b":"b1"},{"c":"c1"}]
2 | [{"a":"f2"},{"b":"b2"},{"c":"c2"}]
3 | [{"a":"f3"},{"b":"b2"},{"c":"c3"}]
4 | [{"a":"f4"},{"b":"b3"},{"c":"v4"}]
5 | [{"a":"f5"},{"b":"b4"},{"c":"c4"}]
结果
`[{"a":"f1"},{"b":"b1"},{"c":"c1"},{"a":"f2"},{"b":"b2"},{"c":"c2"},"a":"f3"},{"b":"b2"},{"c":"c3"}{"a":"f4"},{"b":"b3"},{"c":"v4"}, {"a":"f5"},{"b":"b4"},{"c":"c4"}]`
答案 0 :(得分:1)
t=# select ('['||translate(json_agg(dv)::text,'[]','')||']')::jsonb from d1;
jsonb
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------
[{"a": "f1"}, {"b": "b1"}, {"c": "c1"}, {"a": "f2"}, {"b": "b2"}, {"c": "c2"}, {"a": "f3"}, {"b": "b2"}, {"c": "c3"}, {"a": "f4"}, {"b": "b3"}, {"c": "v4"}, {"a": "f5"}, {"b": "b4"},
{"c": "c4"}]
(1 row)
或更整洁的SQL,但需要一些构建:
create or replace function json_agg_arr(jsonb,jsonb) returns jsonb as $$
select case when coalesce($1::text, '') <> '' then $1 || $2 else $2 end;
$$ language sql called on null input;
create aggregate json_agg_arr (jsonb) (sfunc=json_agg_arr,stype=jsonb);
然后只聚合行:
t=# select json_agg_arr(dv::jsonb) from d1;
json_agg_arr
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------
[{"a": "f1"}, {"b": "b1"}, {"c": "c1"}, {"a": "f2"}, {"b": "b2"}, {"c": "c2"}, {"a": "f3"}, {"b": "b2"}, {"c": "c3"}, {"a": "f4"}, {"b": "b3"}, {"c": "v4"}, {"a": "f5"}, {"b": "b4"},
{"c": "c4"}]
(1 row)