[leetcode]Consecutive Numbers

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. 从Logs表中找出Num连续出现至少3次的数。 sql中设置变量
set @t1=0;
sql中在select中赋值
@t1:= 1
sql中条件判断
case when 条件 then 结果1 else 结果2 end 例如:case when @tp=Num then @t1+1 else 1 end
或者
IF(条件,结果1,结果2) 例如:IF(@tp=Num ,@t1+1 ,1)
可以直接赋值给变量
@t1 := (case when @tp=Num then @t1+1 else 1 end) @t1 := IF(@tp=Num ,@t1+1 ,1)
最终答案 [codesyntax lang="sql"]
select distinct Num as ConsecutiveNums from (select Num from (select @t1 := (case when @tp=Num then @t1+1 else 1 end) as count, @tp := Num as Num from Logs,(select @t1:=0) r,(select @tp:=0) m) t where count>2) o;
[/codesyntax]

你可能感兴趣的:(LeetCode,sql)