Sql 基于描述GPS信息的连续行程

Sql 基于描述GPS信息的连续行程,sql,postgresql,gps,gaps-and-islands,Sql,Postgresql,Gps,Gaps And Islands,假设我们有一个表,其中包含GPS跟踪器定期发送的数据 CREATE TABLE unit_messages (datetime timestamp, speed numeric, trip_distance numeric); 它包含消息发送时的时间戳和速度等,以及行车距离在车辆行驶时增加,停车时重置为0 ('2017-10-26T13:41:41', 0.0, 0.0), ('2017-10-26T13:41:57', 23.0, 0.1), ('2017-10-26T13:42:01',

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

CREATE TABLE unit_messages
(datetime timestamp, speed numeric, trip_distance numeric);
它包含消息发送时的时间戳和速度等,以及行车距离在车辆行驶时增加,停车时重置为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查询生成具有以下签名的行程:

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

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

只需根据距离0.0创建组。检查
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