使用jsonb_build_object()
构建主对象,使用jsonb_agg()
将它们聚合成JSON数组:
select
key,
jsonb_agg(jsonb_build_object('category', category, 'avg_time', avg_time_1)) as avg_time_1,
jsonb_agg(jsonb_build_object('category', category, 'avg_time', avg_time_2)) as avg_time_2
from data_to_agg_json
group by key
key | avg_time_1 | avg_time_2
1 | [{"avg_time": 10, "category": 10}, {"avg_time": 30, "category": 20}] | [{"avg_time": 20, "category": 10}, {"avg_time": 40, "category": 20}]
2 | [{"avg_time": 10, "category": 10}, {"avg_time": 60, "category": 20}] | [{"avg_time": 50, "category": 10}, {"avg_time": 70, "category": 20}]
(2 rows)
Db<>Fiddle.
=>