SQL Medium difficulty practice question : Consecutive Numbers

180Consecutive Numbers 

Hello All, I am back with another SQL leetcode solution. This time we are going one step ahead and practice question with medium difficulty.


Table: Logs

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| num         | varchar |
+-------------+---------+
id is the primary key for this table.
id is an autoincrement column.

 

Write an SQL query to find all numbers that appear at least three times consecutively.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
Logs table:
+----+-----+
| id | num |
+----+-----+
| 1  | 1   |
| 2  | 1   |
| 3  | 1   |
| 4  | 2   |
| 5  | 1   |
| 6  | 2   |
| 7  | 2   |
+----+-----+
Output: 
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+
Explanation: 1 is the only number that appears consecutively for at least three times.

Solution :

# Write your MySQL query statement below
SELECT Distinct L1.num as ConsecutiveNums
FROM Logs L1,
           Logs L2,
           Logs L3
WHERE L1.id = L2.id - 1
and   L2.id = L3.id - 1 
and   L1.num = L2.num
and   L2.num = L3.num


Explanation : 
First we will create 3 objects to represent three different entities in SQL query as L1, L2, L3.

Then, if id of L1 is 1, L2 is 2, L3 is 3 and so on. To refer L1,L2,L3 has 3 consecutive set of ids we will use WHERE clause as follow :

WHERE L1.id = L2.id - 1
and   L2.id = L3.id - 1 

The next condition to satisfy is num represented by L1, L2 and L3 is equal, which further shown by AND statement as follow :

and   L1.num = L2.num
and   L2.num = L3.num

Happy Learning !
For any queries feel free to comment !

Comments

Popular posts from this blog

SQL for beginners : finding out Employees Earning More Than Their Managers

Answer to SQL Leetcode Question 183. Customers Who Never Order