程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SyBase數據庫 >> SyBase教程 >> ConsecutiveNumbers

ConsecutiveNumbers

編輯:SyBase教程

ConsecutiveNumbers


    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 num,@curRank := @curRank+IF(@preNum = num,0,1) as rank ,@preNum:=num from logs s,(select @curRank := 0) r,(select @preNum := null) p;
    +------+------+--------------+
    | num  | rank | @preNum:=num |
    +------+------+--------------+
    |    1 |    1 |            1 |
    |    1 |    1 |            1 |
    |    1 |    1 |            1 |
    |    2 |    2 |            2 |
    |    1 |    3 |            1 |
    |    2 |    4 |            2 |
    |    2 |    4 |            2 |
    +------+------+--------------+
    如上所示,如果一個num的連續排名超過3則符合題意。
    select num,count(rank) as count from (
        select num,@curRank := @curRank+IF(@preNum = num,0,1) as rank ,@preNum:=num from logs s,(select @curRank := 0) r,(select @preNum := null) p ) t 
        group by rank;
    +------+-------+
    | num  | count |
    +------+-------+
    |    1 |     3 |
    |    2 |     1 |
    |    1 |     1 |
    |    2 |     2 |
    +------+-------+
    得到上述的表之後,再使用having條件選擇。
    最終結果:
    select distinct num from(
        select num,count(rank) as count from (
            select num,@curRank := @curRank+IF(@preNum = num,0,1) as rank ,@preNum:=num from logs s,(select @curRank := 0) r,(select @preNum := null) p ) t 
            group by rank having count >= 3;
        ) tmp;
    解法二:
    1、從第一條記錄搜索,前後相同,count++,不相等,count=1;
    2、判斷,若rank大於3則符合題意
    select distinct num 
        from ( 
            select num,@curRank := @preRank+IF(@preNum = num,1,0),@preRank :=IF(@preNum = num,@curRank,1) as rank,@preNum := num 
                from Logs s,(select @preRank := 1) r,(select @preNum := null) p
        ) t 
        where rank >= 3;

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved