如何计算车辆在 sql 中连续位置的时间

How to calculate the time of a vehicle continuously at a location in sql

我已经尝试使用具有最小和最大逻辑的行号。但如果车辆第二次访问同一位置,则失败。

这是一个 gaps-and-islands 问题,您希望将具有相同车辆和位置的相邻行组合在一起。

这是一种使用行号之间的差异来识别孤岛的方法:

select vehicle_no, location, min(time) starttime, max(time) endtime,
    max(time) - min(time) timediff
from (
    select t.*, 
        row_number() over(partition by vehicle_no order by time) rn1,
        row_number() over(partition by vehicle_no, location order by time) rn2
    from mytable t
) t
group by vehicle_no, location, rn1 - rn2

这是一个 gaps-and-islands 问题。在这种情况下,您可以使用 row_number()s 的差异来识别“孤岛”:

select vehicle_no, location, min(time), max(time),
       max(time) - min(time) as at_location
from (select t.*,
             row_number() over (partition by vehicle_no order by time) as seqnum,
             row_number() over (partition by vehicle_no, location order by time) as seqnum_2
      from t
     ) t
group by vehicle_no, location, (seqnum - seqnum_2)