首页 > 解决方案 > Mysql IF 语句检查多个可能为空的值

问题描述

我在使用 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 语句组合成一个大的条件检查。

任何帮助将不胜感激。

标签: mysqlsql

解决方案


用 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"

推荐阅读