mysql - 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 语句组合成一个大的条件检查。
任何帮助将不胜感激。
解决方案
用 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"
推荐阅读
- android - 预训练的 keras 模型在 android 中返回相同的结果
- javascript - 在javascript es6中将嵌套对象转换为递归数组或嵌套数组
- sql - 仅显示来自具有确切三个条目的用户的 SQL 结果
- sql - 如何获取唯一的最大数据
- ruby-on-rails - ActionCable:如何检查用户是否订阅了频道?
- php - 仅在前端检查 WC()->session->has_session() 而不是在 Rest-API 上检查
- python - 我的插入 python 排序总是将第二个数字放在开头
- ios - 代码签名对于证明所有权至关重要吗?
- python - Python按多列压缩行 - groupby 丢弃不应该的组?
- javascript - 在 JHipster (v5.82) 项目中包含自定义类型