JSON_AGG与postgressql

时间:2019-06-13 06:09:51

标签: sql postgresql

我已经如下运行查询

select sum(ts.delay_end_time)as delay_time,dc.id,dc.category_department,
        json_agg(json_build_object('delay_numeric_code',TRIM(dcm.delay_numeric_code),'delay_alphabetic_code',
                                   TRIM(dcm.delay_alphabetic_code),
        'description',dcm.description,'time',ts.delay_end_time)) as des
         from task_status ts
        inner join resource_mapping  rm on rm.id=ts.resource_mapping_id
        inner join flight_schedules  fs on fs.id = rm.flight_schedules_id 
        inner join delay_code_master dcm on dcm.id = ts.delay_code_id
        inner join delay_categorization dc on dc.id = dcm.delay_category_id
        group by dc.id,dc.category_department order by dc.id ASC

但是它返回像 enter image description here

在上述结果中,json数据也应为 delay_numeric_code 组成的组。我该如何实现

i,除了

之类的结果
{  
      "delay_numeric_code":"11",
      "delay_alphabetic_code":"PD",
      "description":"YYYYYYYYYYYYYY",
      "time":34
   },
   {  
      "delay_numeric_code":"17",
      "delay_alphabetic_code":"P0",
      "description":"##########",
      "time":26
   }

来自json

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么您想要类似的东西

SELECT DISTINCT ON (delay_numeric_code)
       /* your select list */
FROM ...
GROUP BY delay_numeric_code, /* others */;

如果您关心使用相同的delay_numeric_code获得的结果,则最好添加适当的ORDER BY子句。