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 | +-----------------+
其实这道题的解法与我在这篇文章中有异曲同工之处:https://www.cnblogs.com/lsyb-python/p/11083828.html,这道题让我们找Num列中连续出现相同数字三次的数字,那么由于需要找三次相同数字,所以我们需要建立三个表的实例,我们可以有a、b和c内交,a和b的id下一个位置比,a和c的下两个位置比,然后将num都相同的数字返回即可:
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;