我想做一个SQL查询
SELECT * from members m where abs(due/30*service_charge)>='0'
AND abs(due/30*service_charge)<='200' group by id
但在某些情况下,service_charge的值将为0,所以我想写一下,如果service_charge = 0,那么service_charge = 1;
有没有办法解决这个问题?。
答案 0 :(得分:3)
使用case
:
select *
from members m
where abs(due/30*(case when service_charge = 0 then 1 else service_charge end) >= 0 and
abs(due/30*(case when service_charge = 0 then 1 else service_charge end)<= 200
group by id;
但是,通常使用NULLIF()
来处理 - 这意味着将从计算中返回NULL
:
select *
from members m
where abs(due / 30 * nullif(service_charge, 0) >= 0 and
abs(due / 30 * nullif(service_charge, 0) <= 200
group by id;
另外,不要在数字常量周围使用单引号。这会让人感到困惑,并且可能会混淆SQL优化器。