首页 > 解决方案 > 语法分组依据

问题描述

我需要计算性能,即 7 月份的最大里程减去 8 月份的最大里程,试试这个查询,它有效但只打印相同的数量。

这是我的查询:

select vehicle_id, max(odometro) as cierre,sum(cantidad) as lts,((select max(odometro) 
      from vehicle_consumptions where fecha between '2020-07-01' and '2020-07-31' group by vehicle_id) - (select max(odometro) from vehicle_consumptions where fecha between '2020-08-01' and '2020-08-30' group by vehicle_id))
       as recorrido,
       ((select max(odometro) 
      from vehicle_consumptions where fecha between '2020-07-01' and '2020-07-31') - 
      (select max(odometro) from vehicle_consumptions where fecha between '2020-08-01' and '2020-08-30'))/sum(cantidad) as rendimiento
        from vehicle_consumptions where EXTRACT(month from fecha)= 08 group by vehicle_id

标签: sqlpostgresqlpivotmaxaggregate-functions

解决方案


我认为你想要条件聚合:

select vehicle_id,
    max(case when fecha < '2020-08-01' then odometro end)
        - max(case when fecha >= '2020-08-01' then odometro end)
    as odometro_diff
from vehicle_consumptions 
where fecha between '2020-07-01' and '2020-08-31'
group by vehicle_id

在 Postgres 中,我们可以使用标准filter子句和日期文字(假设它fecha是类似日期的数据类型 - 应该是这样):

select vehicle_id,
    max(odometro) filter(fecha < date '2020-08-01')
        - max(odometro) filter(where fecha >= date '2020-08-01')
    as odometro_diff
from vehicle_consumptions 
where fecha between date '2020-07-01' and date '2020-08-31'
group by vehicle_id

最后:如果你的日期有时间成分,我会推荐半开间隔,所以where条款应该是:

where fecha >= date '2020-07-01' and fecha < '2020-09-01'

推荐阅读