我有以下代码:
CASE WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5 Then 1 ELSE 0
x和y是列。我的问题是,sum(y)
可以是0,我得到的错误除以0是不可能的。我怎样才能在else子句中赶上这个错误。因此,如果y = 0 "ELSE 0"
被激活。
答案 0 :(得分:2)
也许还有一个条件?
CASE
WHEN sum(y)=0 then 0
WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5 Then 1
ELSE 0
END
答案 1 :(得分:1)
尝试使用表达式NullIf(sum(y), 0)
代替sum(y)
:
select
CASE
WHEN (1+sum(x)/NullIf(sum(y), 0)) >=0
and (1+sum(x)/NullIf(sum(y), 0)) < 0.5 Then 1
ELSE 0
END
答案 2 :(得分:0)
case when
sum(coalesce(y, 0)) <> 0
and (1+sum(x)/sum(coalesce(y, 0))) >= 0
and (1+sum(x)/sum(coalesce(y, 0))) < 0.5 then
1
else
0
end
答案 3 :(得分:0)
您需要先检查分母是否为零 如果是,那么不要计算公式返回零 其他 计算公式
在代码中:
CASE WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5 Then 1
ELSE 0
将其修改为:
CASE
WHEN SUM(isnull(y,0))=0 then 0
ELSE
CASE
WHEN (1+sum(x)/sum(y)) >=0 and (1+sum(x)/sum(y)) < 0.5
THEN 1
END
END AS [RESULT]