6. Consecutive Numbers

Medium
#Window Functions#LEAD#LAG#Self Join

Problem Description

Find all numbers that appear at least three times consecutively in the **Logs** table. Return the result table in any order. ### Example **Logs Table:** | id | num | | :--- | :--- | | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | **Expected Output:** | ConsecutiveNums | | :--- | | 1 |

Database Schema

undefined

Sample SQL Solution

-- Write your SQL query to find consecutive numbers
SELECT DISTINCT num AS ConsecutiveNums
FROM (
    SELECT 
        num,
        LAG(num, 1) OVER (ORDER BY id) AS prev_num,
        LEAD(num, 1) OVER (ORDER BY id) AS next_num
    FROM Logs
) t
WHERE num = prev_num AND num = next_num;