Reputation: 23
Selecting consecutive rows with a column under a certain value
I have a table with the following data:
crashID crash
-----------------------
1 189
2 144
3 8939
4 748
5 988
6 102
7 392
8 482
9 185
10 101
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:
crashID crash
------------------
6 102
7 392
8 482
9 185
10 101
Upvotes: 2
Views: 1818
Reputation: 272006
You can try to solve it using gaps and islands approach, assume every crash lte 500 is an island then find the largest island:
SET @threshold = 500;
WITH cte1 AS (
SELECT
crashID,
CASE WHEN crash <= @threshold THEN 1 ELSE 0 END AS island,
ROW_NUMBER() OVER (ORDER BY crashID) rn1,
ROW_NUMBER() OVER (PARTITION BY CASE WHEN crash <= @threshold THEN 1 ELSE 0 END ORDER BY crashID) rn2
FROM t
), cte2 AS (
SELECT MIN(crashID) AS fid, MAX(crashID) AS tid
FROM cte1
WHERE island = 1
GROUP BY rn1 - rn2
ORDER BY COUNT(*) DESC
LIMIT 1
)
SELECT *
FROM t
WHERE crashID BETWEEN (SELECT fid FROM cte2) AND (SELECT tid FROM cte2);
Upvotes: 2
Reputation: 33935
Here's one way, for older versions of MySQL... This solution assumes no ties for first place...
SELECT m.*
FROM my_table m
JOIN
( SELECT MIN(crash_id) range_start
, MAX(crash_id) range_end
FROM
( SELECT x.*
, CASE WHEN FLOOR(crash/500) * 500 = 0 AND @prev = FLOOR(crash/500) * 500 THEN @i:=@i ELSE @i:=@i+1 END i
, @prev:=FLOOR(crash/500)*500 prev
FROM my_table x
, (SELECT @prev:=null,@i:=0) vars
ORDER
BY crash_id
) a
GROUP
BY i
ORDER
BY COUNT(*) DESC LIMIT 1
) n
ON m.crash_id BETWEEN n.range_start AND n.range_end;
Upvotes: 0