I have table named vehicledata
which consists 3 columns: id
, Veh No
, and Veh Mode
.
My data looks like this:
You can just count the number of rows that have 'DRIVE'
where the previous row has a different mode or NULL. For that, use
lag()`:
select veh_no, count(*)
from (select t.*,
lag(veh_mode) over (partition by veh_no order by id) as prev_veh_mode
from t
) t
where veh_mode = 'DRIVE' and
(prev_veh_mode <> 'DRIVE' or prev_veh_mode is null)
group by veh_no;
Here is a db<>fiddle (which happens to use MySQL but the code should work in any database).