SQL Query to get count of cycles if it matches value of column in consecutive rows

前端 未结 3 925
死守一世寂寞
死守一世寂寞 2021-01-29 08:50

I have table named vehicledata which consists 3 columns: id, Veh No, and Veh Mode.

My data looks like this:



        
3条回答
  •  情深已故
    2021-01-29 09:17

    You can just count the number of rows that have 'DRIVE' where the previous row has a different mode or NULL. For that, uselag()`:

    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).

提交回复
热议问题