I have table named vehicledata
which consists 3 columns: id
, Veh No
, and Veh Mode
.
My data looks like this:
One approach might be to approach this as a gaps and islands problem, and use the difference in row numbers method:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY VehNo ORDER BY id) rn1,
ROW_NUMBER() OVER (PARTITION BY VehNo, VehMode ORDER BY id) rn2
FROM yourTable
)
SELECT VehNo, COUNT(DISTINCT rn1 - rn2) / 2 AS NumCycles
FROM cte
GROUP BY VehNo;
Demo
This assumes that every 2 islands corresponds to one driving cycle. A vehicle having IDLE/DRIVE/IDLE would therefore be counted as having only 1 cycle, since 3 / 2 truncates to 1 in integer division.