Leetcode 180. Consecutive Numbers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013596119/article/details/82015984

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

Answer:

#sol1
select distinct Num as ConsecutiveNums from Logs l where Num=(select Num from Logs where id=l.id-1) and Num=(select Num from Logs where id=l.id-2) 

#sol2
select distinct l1.Num as ConsecutiveNums from Logs l1, logs l2, logs l3 where l1.Num=l2.Num and l1.id-1=l2.id and l1.num=l3.num and l1.id-2=l3.id

猜你喜欢

转载自blog.csdn.net/u013596119/article/details/82015984