[LeetCode#180]Consecutive Numbers

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

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

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

  其實這道題的解法與我在這篇文章中有殊途同歸之處:http://www.javashuo.com/article/p-quklpudm-eu.html,這道題讓咱們找Num列中連續出現相同數字三次的數字,那麼因爲須要找三次相同數字,因此咱們須要創建三個表的實例,咱們能夠有a、b和c內交,a和b的id下一個位置比,a和c的下兩個位置比,而後將num都相同的數字返回便可:html

SELECT a.Num FROM logs as a
JOIN logs as b ON a.Id = b.Id -1
JOIN logs as c on a.Id = c.Id -2
WHERE a.Num = b.Num AND b.Num = c.Num;
相關文章
相關標籤/搜索