有没有办法可以查询表中缺少的数字?

时间:2017-10-12 17:43:38

标签: sql algorithm db2

我在一家物流公司工作,我们必须在每件货物上有一个7位数的Pro编号,这是一个预先确定的订单。所以我们知道这些数字存在差距,但是有什么方法可以查询系统并找出缺少的系统吗?

因此,请显示列名trace_number中不存在的1000000到2000000之间的所有数字。

因此,你可以看到下面的序列是1024397,1024398,然后是1051152所以我知道26k pro数字存在很大差距,但是无论如何只是查询差距?

enter image description here

Select t.trace_number, 
integer(trace_number) as number,
ISNUMERIC(trace_number) as check

from trace as t
left join tlorder as tl on t.detail_number = tl.detail_line_id


where left(t.trace_number,1) in ('0','1','2','3','4','5','6','7','8','9')
and date(pick_up_by) >= current_date - 1 years
and length(t.trace_number) = 7
and t.trace_type = '2'
and site_id in ('SITE5','SITE9','SITE10')
and ISNUMERIC(trace_number) = 'True'


order by 2
fetch first 10000 rows only

2 个答案:

答案 0 :(得分:2)

我不确定您的查询与问题有什么关系,但您可以使用lag() / lead()来确定差距。这个想法是:

select (trace_number + 1) as start_gap,
       (next_tn - 1) as end_gap
from (select t.*,
             lead(trace_number) order by (trace_number) as next_tn
      from t
     ) t
where next_tn <> trace_number + 1;

这不会在范围内找到它们。它只是找到了所有的差距。

答案 1 :(得分:1)

尝试这样的事情(调整where条件,在“on”中加入条款):

with Range (nb)   as (                                   
values 1000000                                                 
union all                                                
select nb+1 from Range                                   
where nb<=2000000                                        
)                                                        
select *                                                 
from range f1 left outer join trace f2       
on f2.trace_number=f1.nb                                  
and f2.trace_number between 1000000 and 2000000                  
where  f2.trace_number is null