sql - 语法分组依据
问题描述
我需要计算性能,即 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
解决方案
我认为你想要条件聚合:
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'
推荐阅读
- c# - C# 错误:控制不能从一个 case label('case0:') 到另一个 case label('case0:')
- windows - 在命令提示符/Windows Powershell (Windows 10) 中使用 UTF-8 编码 (CHCP 65001)
- android - android中webView中的ERR_ACCESS_DENIED
- python - 为什么基于 fft 的卷积总是比空间卷积运行得慢?
- python-3.x - 如何从 mysql 数据库和树视图中删除 python ttk 树视图上的选定项目?
- ssl - 如何为指向另一个服务器 IP 地址的记录子域设置 SSL 证书
- vb.net - 我希望我的自定义类将日志事件传递给调用者 vb.net
- javascript - 如何创建一个新类,我的两个类都将从中继承方法和属性?
- python - 如何在 python 中创建 int 类型的变量实例?
- c++ - C++ CMake未定义的参考链接错误