sql - 如何在查询 SELECT 中进行数学运算?
问题描述
我有一张统计表,其中计算了用水操作。我有三种水0,2,3。但是有0型水,它包括2型、3型和0型,即0型水=0+2+3。也就是说,如果一个水型例如2的操作,那么在数据库I将有一个水类型为 2 的操作和一个水类型为 0 的操作的记录。我没有只有类型 0 的真实记录。我有一个周期标记,当周期为 1 时,我保持计数。我如何对 0 型水进行采样,它应该是这样的 0 = 0-2-3。我试着写这样的东西
SELECT
(SELECT water FROM `production`.statistics where statistical_id = 3133 and created_at >= '2020-10-04 21:00:00' and created_at <= '2020-10-15 21:00:00' and water_type = 0 and period=1) -
(SELECT water FROM `production`.statistics where statistical_id = 3133 and created_at >= '2020-10-04 21:00:00' and created_at <= '2020-10-15 21:00:00' and water_type = 2 and period=1 )-
(SELECT water FROM `production`.statistics where statistical_id = 3133 and created_at >= '2020-10-04 21:00:00' and created_at <= '2020-10-15 21:00:00' and water_type = 3 and period=1 );
但是如果没有对某些类型的水进行操作,我得到的结果为空。我尝试应用 EXIST,但我无法应用它,我经常收到不正确的语法错误。我使用玛丽亚数据库。
解决方案
您可以简化此查询:
select sum(case when water_type = 1 then water
else - water
end)
from `production`.statistics
where statistical_id = 3133 and
created_at >= '2020-10-04 21:00:00' and
created_at <= '2020-10-15 21:00:00' and
period = 1 and
water_type in (1, 2, 3);
这也应该可以解决NULL
问题。
推荐阅读
- react-native - ReactNavigation 错误 - 无法读取未定义的属性“绑定”
- amazon-web-services - 拒绝从 Jenkins shell 脚本激活 AWS EC2 Linux 实例中 virtualenv 中的 python37 的权限
- azure - Azure 自动化如何使用调度程序设置文件共享快照的保留期限?
- google-calendar-api - 如何使用谷歌 API 中的日历名称删除谷歌日历?
- docusaurus - 如何更改 Docusaurus 中的slidingNav 的断点
- c# - C# WebAPI,使用 IIS 的启动任务
- python - 捕获 subprocess.run() 的输入
- html - p 标签在未满之前换行
- git - 如何删除开发中的所有提交并仅获取原始开发中的提交?
- javascript - 由于使用 angular5 和 javascript 的变换属性,无法从 svg 生成 png