これはギャップと島の形です。行番号の違いを使用して、島を取得できます:
select device_id, speed, count(*) as num_times
from (select t.*,
row_number() over (partition by device_id order by datetime) as seqnum,
row_number() over (partition by device_id, speed order by datetime) as seqnum_s
from t
) t
group by device_id, speed, (seqnum - seqnum_s);
次に、最大値を取得するには、ウィンドウ関数の別のレイヤーを使用します。
select device_id, speed, num_times
from (select device_id, speed, count(*) as num_times,
row_number() over (partition by device_id order by count(*) desc) as seqnum
from (select t.*,
row_number() over (partition by device_id order by datetime) as seqnum,
row_number() over (partition by device_id, speed order by datetime) as seqnum_s
from t
) t
group by device_id, speed, (seqnum - seqnum_s)
) ds
where seqnum = 1;