因此,您正在尋找差距,並希望獲得這些差距的第一個值。
這可能是讓他們最好的方式,嘗試與當前TeNr加1,檢查是否有行,如果有你沒有發現它:
select t1.TeNr, t1.TeNr + 1 as unused_TeNr
from tab as t1
left join Tab as t2
on t2.TeNr = t1.TeNr + 1
where t2.TeNr is null
編輯:
要得到你需要使用一些老式的SQL缺失值的範圍爲SQLite的似乎不支持ROW_NUMBER等
select
TeNr + 1 as RangeStart,
nextTeNr - 1 as RangeEnd,
nextTeNr - TeNr - 1 as cnt
from
(
select TeNr,
(select min(TeNr) from tab as t2
where t2.TeNr > t1.TeNr) as nextTeNr
from tab as t1
) as dt
where nextTeNr > TeNr + 1
這是probabl y效率不高,但如果行數很少和/或TeNr上有索引,則可能會有問題。
獲取的差距在結果集的行中的每個值是很辛苦的,如果你的SQLite版本支持遞歸查詢:
with recursive cte (TeNr, missing, maxTeNr) as
(
select
min(TeNr) as TeNr, -- start of range of existing numbers
0 as missing, -- 0 = TeNr exists, 1 = TeNr is missing
max(TeNr) as maxTeNr -- end of range of existing numbers
from tab
union all
select
cte.TeNr + 1, -- next TeNr, if it doesn't exists tab.TeNr will be NULL
case when tab.TeNr is not null then 0 else 1 end,
maxTeNr
from cte left join tab
on tab.TeNr = cte.TeNr + 1
where cte.TeNr + 1 < maxTeNr
)
select TeNr
from cte
where missing = 1
根據您的數據,這可能返回一個巨大的行量。 您也可以使用前一個RangeStart/RangeEnd查詢的結果作爲此遞歸的輸入。
目前尚不清楚。你如何分組?爲什麼沒有100結果輸出? – Uriil
因爲我想獲得最後一個最高值以便能夠選擇下一個值。例如,在這種情況下,TelNr是100到199,200到299,300到399等等。有時數字不見了,所以我可以使用它們。 100不存在,因爲101是在100範圍內發現的第一個最高數字,因爲102失蹤:) – user3808023