首页 > 解决方案 > SQL (Redshift) - 查找连续数字

问题描述

假设我有一个下表:

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

我想找出连续出现 3 次的数字。所以在这个例子中,输出是 1。

当数据中有更多行时,如何使用常规 SQL(而不是 PL/SQL)来实现这一点?

谢谢!

标签: sqlamazon-redshift

解决方案


这应该有效。这是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

推荐阅读