需要查找已删除或缺少列的缺失数字。
例如:
我有一个名为Person的表,其中有[PersonID] [PersonName]列
[PersonID]是主要的且递增的数字,例如从1到N。
PersonID PersonName
1001 ABC
1002 ABC
1003 XYZ
1004 MNO
1006 ABC
1008 MNO
1009 ABC
1010 ABC
1011 XYZ
1014 ABC
1015 ABC
1016 XYZ
1017 MNO
在给定的表中,PersonID列中缺少一些数字,例如
1005
1007
1012
1013
只需查找丢失的号码。
注意:我的表中有超过2000万条记录。 因此,请提出一种更快的方法来找到所需的数字。
答案 0 :(得分:0)
最简单的方法是获取范围。您可以使用lead()
:
select personid + 1, next_personid - 1 as end_range,
next_personid - personid - 1 as num_missing
from (select t.*,
lead(personid) over (order by personid) as next_personid
from t
) t
where next_personid <> personid + 1;
如果您仍然想要ID列表,则可以扩展范围,但这取决于数据库。
在SQL Server 2008中,这需要更多的性能,但是您可以这样做:
select personid + 1, tnext.personid - 1 as end_range,
text.personid - personid - 1 as num_missing
from t cross apply
(select top (1) t2.person_id
from t t2
where t2.personid > t.person_id
order by t2.personid asc
) tnext
where tnext.personid <> personid + 1;
答案 1 :(得分:0)
创建另一个表,并填充PersonID的最小和最大范围之间的所有数字。进行反连接(左/右)以获取缺少的数字列表。
select * from NewIDTable a
left join OriginalTable b on a.PersonID=b.PersonID
where b.Personid is null
答案 2 :(得分:0)
感谢所有支持并分享观点的人。我找到了使用 ROWNUMBER()查找失踪者的方法。
//these part is to pick the date and it work
$("#datetimepicker6").on("dp.change", function(e) {
var drr = $('#datetimepicker6').data('date')
alert(drr);
});
$('#datetimepicker6').datetimepicker({
format: 'DD.MM.YYYY HH:mm:ss',
keyBinds: {'delete': null}
});
//I want to use that result as the minimum of this datatimepicker and to add +7 days as maximum
$('#datetimepicker7').datetimepicker({
format: 'DD.MM.YYYY HH:mm:ss',
//useCurrent: false,
//maxDate: drr,
keyBinds: {'delete': null},
useCurrent: false //Important! See issue #1075
});