首页 > 解决方案 > 如何在查询 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,但我无法应用它,我经常收到不正确的语法错误。我使用玛丽亚数据库。

标签: sqlmariadb

解决方案


您可以简化此查询:

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问题。


推荐阅读