Mysql IF语句检查可能为空的多个值

时间:2018-10-08 05:11:33

标签: mysql sql

我在使用SQL语句时遇到困难。我有一个KPI(关键绩效指标),也可能有一个上限和下限。设置KPI的人可以选择设置两者,或者两者都绑定。我想在仪表板上显示一条消息,该消息一目了然,表明该值是否在范围内。出于我们的目的,可以将空值视为界限,而不必明确打破哪个界限。

所以基本上,我正在尝试构建如下语句:

Check if the kpi_lower_bound is null or not If it is not null, check that the kpi_value > kpi_lower_bound Check if the kpi_upper_bound is null or not If it is not null, check that the kpi_value < kpi_lower_bound

If both statements pass or both are null, return "within bounds". If either statement fails, return "out of bounds."

我可以用类似这样的语句来检查边界的任何一侧

SELECT
IF(kpi_lower_bound IS NOT NULL, (IF(kpi_value < kpi_lower_bound,"Out of lower bounds","Within lower bounds")), "It's null") AS "lower bound break", 

但是我不知道如何将这样的多个if语句合并到一个大的条件检查中。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

尝试使用CASE WHEN

SELECT
cast when kpi_lower_bound IS NOT NULL 
   then case when kpi_value < kpi_lower_bound then 'Out of lower bounds' else 'Within lower bounds' end
else 'It''s null' end AS "lower bound break"

答案 1 :(得分:0)

我们可以尝试使用的一种技巧是使用COALESCE并使用以下逻辑替换缺失的边界:

  1. 缺少下界默认为2147483647
  2. 缺少上限默认为-2147483648

然后使用CASE表达式:

SELECT
    CASE WHEN kpi_value < COALESCE(kpi_lower_bound, -2147483648) OR
              kpi_value > COALESCE(kpi_upper_bound, 2147483647)
         THEN 'out of bounds'
         ELSE 'within bounds' END AS bounds
FROM yourTable;

这里的窍门是,当kpi_lower_boundNULL时,将被-2147483648所取代,即很小的数字,在此以下我们不希望{ {1}}可以达到。这样可以为下限检查自由通行任何kpi_value的{​​{1}}。同样的逻辑也适用于kpi_value值和上限检查。

相关问题