SQL Challenge: Consecutive Numbers with LEAD Function

🗓️ SQL Challenge Day #32: Consecutive Numbers 🔹 Find numbers appearing 3+ times in a row! 🔢 🔹 Problem:   Identify values with ≥3 consecutive occurrences:   ✅ Consecutive = sequential `id` values   ✅ Return distinct numbers only  🔹 Solution (Window Function Approach):  SELECT distinct num AS ConsecutiveNums FROM (     SELECT         num,         id,         LEAD(id) OVER (PARTITION BY num ORDER BY id) AS l1,         LEAD(id, 2) OVER (PARTITION BY num ORDER BY id) AS l2     FROM Logs ) t WHERE l1 - id = 1   AND l2 - l1 = 1; ✅ Result: Accepted  💡 Key Takeaway:   **LEAD() checks sequence gaps!** By comparing current `id` with next two `id`s:   - `l1 - id = 1` → next record is immediate successor   - `l2 - l1 = 1` → third record is also consecutive   ⚠️ Why partition by `num`? Ensures we only compare same numbers!  👇 Your turn:   Have you used LAG/LEAD for detecting sequences in logs or time-series data? What patterns did you find?  #SQL #LeetCode #DataEngineering #ProblemSolving #Coding #LearningInPublic #Database #DataAnalytics

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories