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

前端 未结 3 930
死守一世寂寞
死守一世寂寞 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:27

    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.

提交回复
热议问题