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.
Solution:
select distinct L1.Num as ConsecutiveNums
from Logs L1
join Logs L2 on L1.Id = L2.Id -1
join Logs L3 on L1.Id = L3.Id -2
where L1.Num = L2.Num and L1.Num = L3.Num
Note: 刚开始用markdown,编辑这篇文章学会的:
“```” 跟 tab 键区别是 “```”是默认代码格式,会标注行数。tab表示高亮文本。上文的文本格式的table用 ``` 无法对齐,用tab就可以了。