【问题标题】:How can you find the first break in a sequence of integer numbers?如何找到整数序列中的第一个中断点?
【发布时间】:2013-02-12 02:36:06
【问题描述】:

假设您有以下表格:

create table #myvalues(mykey int primary key)

您还具有以下值:

insert into #myvalues(mykey) values(1)
insert into #myvalues(mykey) values(2)
insert into #myvalues(mykey) values(4)
insert into #myvalues(mykey) values(5)
insert into #myvalues(mykey) values(6)
insert into #myvalues(mykey) values(8)
insert into #myvalues(mykey) values(10)
insert into #myvalues(mykey) values(11)
insert into #myvalues(mykey) values(12)
insert into #myvalues(mykey) values(15)
insert into #myvalues(mykey) values(17)
insert into #myvalues(mykey) values(20)

你还有一个当前值:

declare @currentvalue int

select @currentvalue = 5

我想找到这个序列中出现在@currentvalue 之后的第一个中断。在这种情况下,答案是 7。

我可以使用表变量并使用 while 循环遍历记录,但必须有更好的方法。

有什么建议吗?

【问题讨论】:

  • 你使用的是什么 sql-server 版本?
  • SQL Server 2005。我刚刚更新了标签。

标签: sql tsql sql-server-2005 integer


【解决方案1】:
WITH list
AS
(
    SELECT  myKey,
            ROW_NUMBER() OVER (ORDER BY myKey ASC) rn
    FROM    #myvalues
)
SELECT  TOP 1 rn
FROM    list
WHERE   myKey <> rn

这是占用starting value的查询

DECLARE @currentValue INT 
SET @currentValue = 5

;WITH list
AS
(
    SELECT  myKey,
            ROW_NUMBER() OVER (ORDER BY myKey ASC) + (@currentValue - 1) rn
    FROM    myvalues
    WHERE   myKey >= @currentValue 
)
SELECT  TOP 1 rn 
FROM    list
WHERE   myKey <> rn

【讨论】:

  • 不考虑currentvalue。它还会在第二个间隙上产生不正确的结果。
  • 如果您将currentValue 更改为 8,正确的结果应该是 13(恕我直言)。
  • @TimSchmelter 我认为当起始值为8 时是9。让我们参考OP
  • @codingguy3000 有什么问题?
【解决方案2】:

你可以自己加入表格:

select top 1 t.mykey + 1
from myvalues t
left join myvalues x on x.mykey = t.mykey + 1
where t.mykey > @currentvalue and x.mykey is null
order by t.mykey

演示:http://www.sqlfiddle.com/#!2/c6dd2/7

【讨论】:

    【解决方案3】:
    select top 1 myKey+1 from #myvalues
    where 
        (myKey+1) not in (select mykey from #myvalues)
        and mykey >= @currentValue
    

    【讨论】:

    • 当我尝试这个解决方案时,为什么当起始值为8时它返回13而不是9
    • 我错过了那个错误。我在我的生产数据上对其进行了测试,因为差距大于 1。
    • 已修复:只需要 >= 而不是 >
    猜你喜欢
    • 2018-04-11
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多