Skip to content
Advertisement

Select consecutive rows under a certain value in MySQL

Selecting consecutive rows with a column under a certain value

I have a table with the following data:

I want to select the longest streak of consecutive rows that also have a crash value below a certain treshold. Let’s say 500 for this example.

How do I go about doing this in a single MySQL query? (v8.0.1)

Desired output would be this:

Advertisement

Answer

You can try to solve it using gaps and islands approach, assume every crash lte 500 is an island then find the largest island:

DB Fiddle

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement