diff --git a/README.md b/README.md index 42f5179..72e2f7d 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ Have a good contributing! - [2356. Number of Unique Subjects Taught by Each Teacher](./leetcode/easy/2356.%20Number%20of%20Unique%20Subjects%20Taught%20by%20Each%20Teacher.sql) 2. [Medium](./leetcode/medium/) - [176. Second Highest Salary](./leetcode/medium/176.%20Second%20Highest%20Salary.sql) + - [180. Consecutive Numbers](./leetcode/medium/180.%20Consecutive%20Numbers.sql) - [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql) - [550. Game Play Analysis IV](./leetcode/medium/550.%20Game%20Play%20Analysis%20IV.sql) - [570. Managers with at Least 5 Direct Reports](./leetcode/medium/570.%20Managers%20with%20at%20Least%205%20Direct%20Reports.sql) diff --git a/leetcode/medium/180. Consecutive Numbers.sql b/leetcode/medium/180. Consecutive Numbers.sql new file mode 100644 index 0000000..5c455a8 --- /dev/null +++ b/leetcode/medium/180. Consecutive Numbers.sql @@ -0,0 +1,35 @@ +/* +Question 180. Consecutive Numbers +Link: https://leetcode.com/problems/consecutive-numbers/description/?envType=study-plan-v2&envId=top-sql-50 + +Table: Logs + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| num | varchar | ++-------------+---------+ +In SQL, id is the primary key for this table. +id is an autoincrement column starting from 1. + + +Find all numbers that appear at least three times consecutively. + +Return the result table in any order. +*/ + +WITH prev_next AS ( + SELECT + id, + LAG(num) OVER(ORDER BY id) AS prev_num, + LEAD(num) OVER(ORDER BY id) AS next_num + FROM Logs +) + +SELECT DISTINCT l.num AS ConsecutiveNums +FROM Logs AS l +LEFT JOIN + prev_next AS pn + ON l.id = pn.id +WHERE l.num = pn.prev_num AND pn.prev_num = pn.next_num