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;