【问题标题】:Get all missing numbers in the sequence获取序列中所有缺失的数字
【发布时间】:2014-05-16 02:44:40
【问题描述】:

数字最初是字母数字,所以我有一个查询来解析数字:

我在这里的查询给了我一个数字列表:

select distinct cast(SUBSTRING(docket,7,999) as INT) from [DHI_IL_Stage].[dbo].[Violation] 其中 InsertDataSourceID='40' 和 ViolationCounty='Carroll' and SUBSTRING(docket,5,2)='TR' and LEFT(docket,4)='2011' order by 1

返回解析出来的数字列表。 例如,编号为 2012TR557。使用查询后将是​​ 557。

我需要编写一个查询,它将按顺序返回缺失的数字。

【问题讨论】:

  • 请提供一些示例数据和预期结果。

标签: sql sql-server sequence


【解决方案1】:

这是一种方法 以下应为每个缺失数字序列返回一行。所以,如果你的系列是 3、5、6、9,那么它应该返回:

4     4
7     8

查询是:

with nums as (
       select distinct cast(SUBSTRING(docket, 7, 999) as INT) as n,
              row_number() over (order by cast(SUBSTRING(docket, 7, 999) as INT)) as seqnum
       from [DHI_IL_Stage].[dbo].[Violation]
       where InsertDataSourceID = '40' and
             ViolationCounty = 'Carroll' and
             SUBSTRING(docket,5,2) = 'TR' and
             LEFT(docket, 4) = '2011'
     )
select (nums_prev.n + 1) as first_missing, nums.n - 1 as last_missing
from nums left outer join
     nums nums_prev
     on nums.seqnum = nums_prev.seqnum + 1
where nums.n <> nums_prev.n + 1 ;

【讨论】:

  • 感谢您的反馈,它无法将 nums_prev 识别为列名。
猜你喜欢
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
  • 2019-03-21
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
相关资源
最近更新 更多