基于离散 GPS 消息的连续行程

Continous trips based on descrete GPS messages

假设我们有一个 table,其中包含 GPS 跟踪器定期发送的数据。

CREATE TABLE unit_messages
(datetime timestamp, speed numeric, trip_distance numeric);

它包含 timestamp 消息发送时,速度等和 trip_distance 在汽车行驶和重置时增长停止时为 0。

('2017-10-26T13:41:41', 0.0, 0.0),
('2017-10-26T13:41:57', 23.0, 0.1),
('2017-10-26T13:42:01', 11.0, 0.1),
('2017-10-26T13:42:18', 20.0, 0.2),
('2017-10-26T13:42:33', 56.0, 0.4),
('2017-10-26T13:42:41', 58.0, 0.5),
('2017-10-26T13:43:13', 0.0, 0.6),
...
('2017-10-26T14:03:38', 12.0, 13.5),
('2017-10-26T15:21:52', 0.0, 0.0)

目标是使 SQL 查询生成具有此类签名的 TRIP:

from_date, to_date, trip_distance

其中 from_date 是 trip_distance=0
时的日期时间 (2017-10-26T13:41:41 第一行)
to_date 是 trip_distance 变为 0
之前最后一行的日期时间 (就像在最后一行 ('2017-10-26T14:03:38', 12.0, 13.5) 之前)

我唯一的解决方案是在循环中顺序迭代 SELECT 的结果。 有人知道 ide 如何通过 SQL 做到这一点吗?

WITH cte as (
    SELECT *, 
           COUNT(CASE WHEN trip_distance = 0 THEN 1 END) 
           OVER (ORDER BY datetime) as grp
    FROM unit_messages 
)
SELECT MIN(datetime), MAX(datetime), MAX(trip_distance)
FROM cte
GROUP BY grp