【问题标题】:Check Range from table where arithmetic operators are also in the same table检查算术运算符也在同一个表中的表范围
【发布时间】:2019-03-30 09:37:06
【问题描述】:

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

col3col1 相关,col4col2 相关。

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

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

【问题讨论】:

  • 对于输入15 - Approved55 - Conditionally Approved, 31 - Rejected, 预期?

标签: sql tsql sql-server-2008


【解决方案1】:

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

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 与您的样本数据:

声明@输入整数; 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 | | :------- | |批准 |

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

【讨论】:

    【解决方案2】:

    如果问题真的是如何计算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;
    

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

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多