如何找到丢失的序列号?

时间:2017-03-02 04:18:07

标签: sql oracle

我有一个包含NVARCHAR2数据类型的列。它在顺序值中增加1,并且具有模式“D2017 \ S \ S \ S \ S”,从0000开始并继续向上。现在我有一直到D20179999的值,但是我错过了从D20170001到D20179999的10个值,我怎样才能找到这些值?

1 个答案:

答案 0 :(得分:2)

这就是你需要的。首先,您应该生成从D20170001D20179999的范围。然后,您必须将此连接与顺序列连接,并找到null以获取缺失的范围。

select * from your_table y
right join  
(select 'D2017'||lpad(to_char(level),4,'0') as c_range
      from dual connect by level < 10000) dt
on y.<range_column>=dt.c_range
where y.<range_column> is null

编辑:根据@mathguy,为了获得更好的性能,请使用

select * from 
(select 'D2017'||lpad(to_char(level),4,'0') as c_range
      from dual connect by level < 10000) dt
 where dt.c_range not in (select <range_column> from your_table)

我将其复制了10个值,但您可以将其扩展为10000个。

with rt (e_range) as (
select 'D20179990' from dual union all
select 'D20179991' from dual union all
select 'D20179992' from dual union all
select 'D20179994' from dual union all
select 'D20179995' from dual union all
select 'D20179997' from dual union all
select 'D20179998' from dual union all
select 'D20179999' from dual)
select c_range from rt
right join (select 'D2017999'||to_char(level) as c_range from dual connect by level < 10) dt
on rt.e_range=dt.c_range
where rt.e_range is null

输出

C_RANGE
D20179993
D20179996