2015-09-03 39 views
-3

在一个大日志文件中,我有包含字段INVNO(发票号码)的记录。
最低和最高值很容易找到,但它看起来像一些
之间的数字不存在。

任何人都有一个SQL技巧,它可以告诉哪些数字在数字范围内丢失?使用SQL查找缺失的数字

+0

您的列名可以尝试在Excel中执行此操作:http://www.extendoffice.com/documents/excel/1054-excel-identify-missing-numbers-sequence.html –

+0

INVNO是整数吗? – jarlh

+0

至少,编辑您的问题与样本数据和所需的结果。 –

回答

0

请使用下表值函数,它有两个参数:最小和最大数, 并返回失踪数的列表, 假设你的表名是YOUR_TABLE并呼吁InvNo

create FUNCTION [dbo].[MissingInvoiceNumbers] 
(
    @minPaym bigint, 
    @MaxPaym bigint 
) 
RETURNS @tmp table(numbers bigint) 

AS 


BEGIN 
declare @n bigint [email protected] bigint , @MaxPaym bigint, 
declare @tmpAll table(Allnumbers bigint) 

set @n= @minPaym 
delete @tmp 
delete @tmpAll 

while (@n<[email protected]) 
begin 
INSERT INTO @tmpAll 
         (AllNUMBERS) 
VALUES  (@n) 
set @[email protected]+1 
end 

INSERT INTO @tmp 
         (numbers) 
SELECT  Allnumbers 
FROM   @tmpAll 
where Allnumbers not in (select distinct convert(bigint,InvNo) as InvoiceNum from YOUR_TABLE where 
InvNo <> '') 

return 
END 
-1

刚刚加入本身的表...

DECLARE @tvp TABLE (INVNO INT) 
INSERT INTO @tvp 
VALUES (1), 
     (2), 
     (3), 
     (5), 
     (6), 
     (7), 
     (8), 
     (9), 
     (10), 
     (11) 

SELECT * 
FROM @tvp; 


SELECT t.INVNO + 1 
FROM @tvp t 
     LEFT OUTER JOIN @tvp x ON x.INVNO = t.INVNO + 1 
WHERE ISNULL(x.INVNO, 0) = 0; 
+1

没有桌子... –

+0

有一张桌子。 – PrivatePyle

0

对于Oracle这应该工作。对于任何其他数据库,您只需更改生成数字序列的方式即可。

with vals as (
    select rownum r 
    from dual 
connect by rownum between {min} and {max} 
) 

select * 
from vals v 
left join {sometable} s on s.{someid} = v.r 
where s.{someid} is null 

诀窍就是产生最小和最大值之间的数字,与发票连接表这个生成的序列,并筛选出相匹配的一切。