SQL:检查数字是否在多个范围内

时间:2018-07-19 01:58:30

标签: sql sql-server

假设我们有2张桌子。

Table Values
Id   Group    Value
--------------------
A     X        15  
B     Y        55

Table Ranges
Group   LowLimit     HighLimit
--------------------------------
X         0             10       
X         20            30 
Y         30            40 
Y         50            60         

我想检查哪些Values.Id的值不在Ranges所属组的LowLimit和HighLimit范围内(注意每个组都有多个范围)。

所需的结果将是

Table Result
Id
--------------
A    (because the value 15 is outside the range of both (0..10) and (20..30) 
while B is not part of the result because it is within the range of (50..60) even though it is outside the range of (30..40))

sql是什么样的?

1 个答案:

答案 0 :(得分:3)

一个选项使用存在查询:

SELECT
    v.ID
FROM [Values] v
WHERE NOT EXISTS (SELECT 1 FROM [Ranges] r
                  WHERE v.[Group] = r.[Group] AND
                        v.[Value] BETWEEN r.[LowLimit] AND r.[HighLimit]);

Demo

以简单的英语,它将检查ID中的每个Values行,并检查它是否不存在,甚至一个包含该值的范围也不存在。如果不存在这样的范围,则将报告此不匹配的ID