查找范围内缺失的数值[重复]

Posted

技术标签:

【中文标题】查找范围内缺失的数值[重复]【英文标题】:Find missing numerical values in range [duplicate] 【发布时间】:2014-02-18 11:00:08 【问题描述】:

我读过几篇文章,其中一个普通程序员犯的错误是没有利用 SQL 的潜力,从那时起,我开始寻找用 SQLish 解决方案替换我的部分代码,而不是使用编程语言获取数据和处理,尽管我是一个真正的 SQL 菜鸟。

假设我有一个随机填充 0 到 10 值的表,我想知道该范围内缺少哪些值。

例如,该表包含以下值:0, 1, 3, 4, 5, 7, 8, 9

查询应返回:2, 6, 10

【问题讨论】:

IDK 你的编程水平是多少,但如果你愿意接受一些建议,我可以保证你会遇到这样的问题:“我开始寻找替换部分代码使用 SQLish 解决方案”。 是哪个数据库系统? 【参考方案1】:

[F5]解决方案(假设是sql server):

-- table with id=0..10 
drop table #temp 
GO
create table #temp (
    id int not null identity(0,1),
    x int
)
GO
insert into #temp (x) values(0)
GO 11


-- your number:
drop table #numbers
GO
select
    *
into #numbers
from (
    select 0 as n union all select  1 union all select  3 union all select  4 union all select  5 union all select  7 union all select  8 union all select  9
) x
GO

-- result:
select 
    * 
from #temp t
left join #numbers n
    on t.id=n.n
where 1=1
    and n.n is null 

【讨论】:

@DrCopyPaste 只是我的习惯 :)。 我是这么想的,但它是从哪里来的呢?是否有一些罕见的情况可以为您带来巨大的好处?只是好奇,也许值得养成这个习惯:D @DrCopyPaste OK :)。 1) 如果您有 2 个and 条件,您可以在不中断查询的情况下评论第一个条件(否则您将留下where and)。 2)它提高了可读性。如果有多个and 条件,它们都很好地对齐。但是如果有很多嵌套的and's 和or's,它会变得非常混乱。所以我使用1=1 and... and...1=2 or... or... 来获得良好的条件结构。 ty 用于清除它,是有道理的;)【参考方案2】:

此解决方案使用 SQL-Server-Syntax(但 AFAIK 仅 GO 特定于 SQL Server Management Studio)

我会加入一个表值函数,它可以让你获得一定范围内的所有数字 (example fiddle):

CREATE FUNCTION dbo.GetNumbersInRange(@Min INT, @Max INT)
        RETURNS @trackingItems TABLE (Number INT) 
        AS BEGIN

        DECLARE @counter INT = @Min

        WHILE (@counter <= @Max)
        BEGIN
          INSERT INTO @trackingItems (Number) SELECT @counter

          SELECT @counter = @counter + 1

        END

        RETURN

        END
        GO

作为一个例子,我设置了一个包含一些数字(有间隙)的表格

CREATE TABLE MyNumbers (Number INT)

INSERT INTO MyNumbers (Number)
  SELECT 1
  UNION
  SELECT 2
  UNION
  SELECT 4
  UNION
  SELECT 5
  UNION
  SELECT 7
  UNION
  SELECT 8

要查找丢失的数字,您可以像这样使用LEFT JOIN

SELECT
        AllNumbers.Number
      FROM GetNumbersInRange(1, 10) AS AllNumbers
      LEFT JOIN MyNumbers ON AllNumbers.Number = MyNumbers.Number
      WHERE MyNumbers.Number IS NULL

【讨论】:

以上是关于查找范围内缺失的数值[重复]的主要内容,如果未能解决你的问题,请参考以下文章

在分布式阵列系统中查找缺失的数字

在 O(1) 空间中的数组中查找重复元素(数字不在任何范围内)

在线性时间和恒定空间中查找数组中缺失和重复的元素

在未排序的数组 1 到 100 中查找 2 个缺失的数字。(Java)[重复]

EXCEL函数如何查找数值在工作表中的位置?

Rails Autocomplete Jquery (crowdint):选择 .uniq 不在范围内工作,避免重复