postgres 9.6-从多个列创建对象JSON数组

时间:2018-07-22 16:17:48

标签: postgresql aggregate-functions jsonb postgres-9.6

我这里有以下数据集

http://sqlfiddle.com/#!17/70f9a/1

我想创建一个查询,结果如下:

  • 键:1,avg_time_1:[{“ category”:10,“ avg_time”:10},{“ category”:20,“ avg_time”:20}], avg_time_2:[{“ category”:10,“ avg_time”:20},{“ category”:20,“ avg_time”:40}]
  • 键:2,avg_time_1:[{“ category”:10,“ avg_time”:10},{“ category”:20,“ avg_time”:60}]], avg_time_2:[{“ category”:10,“ avg_time”:50},{“ category”:20,“ avg_time”:70}]
  • 这个想法只是以不同的方式(jsonb值)重新显示cols avg_time_1和avg_time_2值

    1 个答案:

    答案 0 :(得分:1)

    使用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)    
    

    SqlFiddle.