简体   繁体   中英

SQL (Redshift) - Find consecutive numbers

Suppose I have a table below:

ID  NUM
 1   1
 2   1
 3   1
 4   2
 5   3 
 6   1

I want to find which number(s) appears 3 times in a row. So in this example the output is 1.

How can I achieve this using regular SQL (not PL/SQL), when I have way much more rows in the data?

Thanks!

You can use lag() :

select num
from (select t.*,
             lag(num) over (order by id) as num_1,
             lag(num, 2) over (order by id) as num_2
      from t
     ) t
where num_1 = num and num_2 = num;

Here is another fun method:

select num
from (select t.*,
             lag(id, 2) over (order by id) as id_2_by_id,
             lag(id, 2) over (partition by num order by id) as id_2_by_id_num
      from t
     ) t
where num = id_2_by_id_num and num_2_by_id = id_2_by_id_num;

This should work. here is the sqlfiddle

select
    distinct num as ConsecutiveNums
from
(
    select
        num,
        count(*) as total
    from
    (
        select
            num,
            id - row_number() over (partition by num order by id) as rnk
        from myTable
    ) t
    group by
        num,
        rnk
) tt
where total > 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM