180. Consecutive Numbers

xiaoxiao2021-02-28  118

题目:

找出连续出现大于或等于3次的数字。 表Logs

IdNum11213142516272

例如:1连续出现3次,结果如下。

ConsecutiveNums1

解析

表内的联系,通常采用表的自连接。题目中主要涉及表内连续3次出现同一数字,那么就需要3张表做连接。

select distinct a.num as ConsecutiveNums 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

表a,b,c分别代表了第一次出现的数字,第二次出现的数字以及第三出现的数字。如果三次都相同,那么即为该数连续出现3次。此外,如果连续出现3次以上那么就会输出多个相同的满足条件的值,因此需要distinct去重。 另一种解法为:

select distinct a.Num as ConsecutiveNums from Logs as a, Logs as b, Logs as c where a.Num = b.Num and b.Num = c.Num and a.Id=b.Id-1 and b.Id= c.Id-1
转载请注明原文地址: https://www.6miu.com/read-84889.html

最新回复(0)