检查来自 table 的范围,其中算术运算符也在相同的 table 中

Check Range from table where arithmetic operators are also in the same table

如何从名为 table 的 table 中获取整数输入

的 col5 值

col3col1 相关,col4col2 相关。

col1   col2     col3    col4     col5
75       0       <               Approved
50      70       >       <       Conditionally Approved
20      50       >       <       Rejected

如果我输入 74,我的预期输出是 col5 值 ('approved')。

我认为以下查询应该可以解决问题:

SELECT col5
FROM mytable
WHERE    
    ( 
        col3 IS NULL 
        OR (col3 = '<' AND @input < col1) 
        OR (col3 = '>' AND @input > col1) 
    ) AND ( 
        col4 IS NULL 
        OR (col4 = '<' AND @input < col2) 
        OR (col4 = '>' AND @input > col2) 
    )

Demo on DB Fiddle 使用您的示例数据:

声明@input INTEGER; SET @input = 74;

SELECT col5
FROM mytable
WHERE    
    ( 
        col3 IS NULL 
        OR (col3 = '<' AND @input < col1) 
        OR (col3 = '>' AND @input > col1) 
    ) AND ( 
        col4 IS NULL 
        OR (col4 = '<' AND @input < col2) 
        OR (col4 = '>' AND @input > col2) 
    )


GO
| col5     |
| :------- |
| Approved |

注意:您的时间间隔存在差异。例如,20 到 50 之间的值通常会匹配两条记录(0-75 和 20-50)。

如果问题真的是如何计算col5那么下面的代码是适用的:

declare @Value as Int = 74;

select col1, col2, col3, col4,
  case
    when col3 = '<' and @Value < col1 and col4 = '' then 'Approved'
    when col3 = '>' and @Value > col1 and col4 = '<' and @Value < col2 then 'Conditionally Approved'
    else 'Rejected' end as col5
  from mytable;

请注意,假设样本数据涵盖所有案例,并且任何批准失败都会导致 "Rejected"。可以添加额外的 when 子句来处理额外的比较和状态 returns.