[我有一个名为tc_fuel
的表,该表正在从GPS车辆接收所有与燃料相关的数据,我想获取最后的“燃料箱使用情况”,以计算整个燃料箱的MPG,但是当燃料箱已满时的读数( 100)在2或3或更多行之后重复一些,所以我剩下2个彼此相邻的100值,我希望能够获得最后一个“填充”开始和结束ID。
到目前为止我所拥有的:
SELECT
"tc_fuel".deviceid,
"tc_fuel"."id",
"tc_fuel".fuel,
"tc_fuel"."fuelUsed",
"tc_fuel"."fuelUsed"
FROM "tc_fuel"
WHERE fuel=100
AND deviceid=19
ORDER BY ID
DESC LIMIT 2
然后,我进入PHP检查ID差是否超过100条记录,以检查燃料值是否彼此相邻,但这比我想知道是否有更好的方法要多得多。
例如,这辆车从满油箱开始,然后下降到6%的油箱并充满了油箱,我希望能够获取最后一个油箱的所有数据。
id | deviceId | fuel
------+-----------+-------
1 | 19 | 100 <-- This should be starting point
2 | 19 | 97
3 | 19 | 100
4 | 19 | 96
5 | 19 | 94
6 | 19 | .... (keeps dropping)
7 | 19 | 33
8 | 19 | 31
9 | 19 | 30
10 | 19 | ....
11 | 19 | 6
12 | 19 | 5
13 | 19 | 6 <-- This should be end point (will flag this id as processed)
14 | 19 | 100 <-- Starts all over again in next iteration of the php script
15 | 19 | 99
16 | 19 | 98
17 | 19 | 100
18 | 19 | 99
19 | 19 | 97
20 | 19 | 96
21 | 19 | ....
SELECT min(id) AS first_id,
max(id) AS last_id,
deviceid
FROM (SELECT id, deviceid, fuel,
count(*) FILTER (WHERE refilled)
OVER (PARTITION BY deviceid ORDER BY id DESC) AS filling
FROM (SELECT id, deviceid, fuel,
fuel < lead(luel, 1, 0)
OVER (PARTITION BY deviceid ORDER BY id) AS before_fill
FROM tc_fuel
) AS refill
) AS fills
WHERE filling = 1
GROUP BY deviceid;
“填充”的定义有点含糊。我假设当燃油值增加超过50