LeetCode | Consecutive Numbers

来源:互联网 发布:网络大电影宣发公司 编辑:程序博客网 时间:2024/06/15 14:30

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.


SELECT DISTINCT Num FROM (
  SELECT Num, COUNT(Rank) AS Cnt FROM (
    SELECT    Num,
      @curRank := @curRank + IF(@prevNum = Num, 0, 1) AS rank, @prevNum := Num
    FROM      Logs s, (SELECT @curRank := 0) r, (SELECT @prevNum := NULL) p
    ORDER BY  ID ASC
  ) t GROUP BY Rank HAVING Cnt >= 3 
) n;

应该好好看看MySQL用户定义变量和聚组函数了

0 0
原创粉丝点击