【SQL刷題系列】:leetcode180 Consecutive Numbers

▌刷題回顧app


【SQL刷題系列】:leetcode178 Rank Scores
ide

【SQL刷題系列】:leetcode183 Customers Who Never Order
spa


▌題目描述3d


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

寫一段SQL查詢語句,找到全部出現至少連續三次的數字。orm


+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+


For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.three

例如,給定上面的logs表,其中 「1」 是惟一一個出現至少連續三次的數字。ci


+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

▌參考答案leetcode


參考1:get

select distinct (l1.Num) as ConsecutiveNums 
from Logs l1
left join Logs l2 on l1.Id = l2.Id - 1
left join Logs l3 on l1.Id = l3.Id - 2
where l1.Num = l2.Num and l2.Num = l3.Num;


參考2:

Select distinct(l1.num) as consecutivenums 
from Logs l1, Logs l2, Logs l3 
where l1.num = l2.num and l2.num = l3.num and 
l2.id = l1.id+1 and l3.id = l2.id+1;


▌答案解析


參考1:建立將3個自鏈接表,並經過減法把3個表中3個連續id鏈接起來。最後使用where條件限制3個連續id對應的num值相等。


參考2:其實和參考1是一個思路,不一樣的地方是自鏈接是徹底按照原有id來鏈接的,沒有錯位,而錯位的地方在where的限制條件中:3個id的大小順序用加法實現。

相關文章
相關標籤/搜索