Consecutive Numbers

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

Return the result table in any order.

Example

Table: Logs
+----+-----+
| Id | Num |
+----+-----+
1  | 1   |
2  | 2   |
3  | 1   |
4  | 1   |
5  | 2   |
6  | 2   |
7  | 2   |
+----+-----+
Output
+-----------------+
| ConsecutiveNums |
+-----------------+
2               |
+-----------------+

Approach:

Mysql

// Number comming three or greater then three time continue
SELECT DISTINCT l1.Num As ConsecutiveNums
FROM Logs l1, Logs l2, Logs l3
WHERE l1.Num = l2.Num 
    AND l2.Num = l3.Num 
    AND l1.Id = l2.Id + 1 
    AND l2.Id = l3.Id + 1;

Oracle

// Number comming three or greater then three time continue
SELECT DISTINCT l1.Num As ConsecutiveNums
FROM Logs l1, Logs l2, Logs l3
WHERE l1.Num = l2.Num 
    AND l2.Num = l3.Num 
    AND l1.Id = l2.Id + 1 
    AND l2.Id = l3.Id + 1;


No comments:

Post a Comment