如何检查想要的跳过缺失的数字序列

时间:2017-07-03 09:32:40

标签: sql oracle gaps-and-islands

基于:How to check any missing number from a series of numbers?

我有一个类似的问题。我的源表有一个从1到1000的序列。 但是如果间隙> 1且<20则仅是坏的。我无法让CONNECT BY工作。

请帮帮我。

SELECT 
    'XX' AS NETWORK
    ,'YY' AS TYPE
    ,min_seq - 1 + level AS MISSING
FROM ( 
    select 
        min(s.SEQUENCE_NUMBER) min_seq
        , max(s.SEQUENCE_NUMBER) max_seq
    FROM source s
)
CONNECT BY level <= max_seq - min_seq +20 AND level >= max_seq - min_seq +1
MINUS 
SELECT 
    'XX' AS NETWORK
    ,'YY' AS TYPE
    ,s.SEQUENCE_NUMBER AS EXISTING
FROM source s 

2 个答案:

答案 0 :(得分:0)

使用CTE(带声明):

with CTE as
(
select level as NN
from dual
connect by level <= 20
)

select CTE.NN
from CTE 
left join source s
  on CTE.NN = s.SEQUENCE_NUMBER
where s.SEQUENCE_NUMBER is null

答案 1 :(得分:0)

旧学校connect by

with tn as(
    -- sample data
    Select 1 n from dual
    union all
    Select 4  from dual
    union all
    Select 26  from dual
    union all
    Select 30  from dual
    union all
    Select 52  from dual
)
select distinct n, delta, n+level nn
from (
    select n, delta
    from (
        select n, lead(n) Over(order by n) - n delta
        from tn) t
    where delta between 2 and 20
    ) t2
connect by level < delta 
order by n