180. Consecutive Numbers


Posted by ikl258794613 on 2024-02-26

Table: Logs

Column Name Type
id int
num varchar

In SQL, id is the primary key for this table.
id is an autoincrement column.

Find all numbers that appear at least three times consecutively.

Return the result table in any order.

The 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.


SELECT l1.num AS ConsecutiveNums
FROM Logs l1
LEFT JOIN Logs l2
ON (L1.id+1) = l2.id
LEFT JOIN Logs l3
ON (L1.id+2) = l3.id
WHERE l1.num = l2.num AND l2.num = l3.num
GROUP BY l1.num

解題思路:
先把自己join起來,在把l1.num = l2.num AND l2.num = l3.num取出來


SELECT *
FROM Logs l1
LEFT JOIN Logs l2
ON (L1.id+1) = l2.id
LEFT JOIN Logs l3
ON (L1.id+2) = l3.id
id num id num id num
1 1 2 1 3 1
2 1 3 1 4 2
3 1 4 2 5 1
4 2 5 1 6 2
5 1 6 2 7 2
6 2 7 2 null null
7 2 null null null null

#SQL







Related Posts

[第九週] PHP 與 MySQL 的互動:新增資料

[第九週] PHP 與 MySQL 的互動:新增資料

Bicycle Kinematic Model 實作小筆記

Bicycle Kinematic Model 實作小筆記

我要成為前端工程師的學習筆記:HTML & CSS 篇 - 文字排版、線條 Day4

我要成為前端工程師的學習筆記:HTML & CSS 篇 - 文字排版、線條 Day4


Comments