我有以下代码:
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"
被激活。
我有以下代码:
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"
被激活。
也许还有一个条件?
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
尝试使用表达式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
您需要先检查分母是否为零如果是则不计算公式返回零否则计算公式
在代码中:
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]
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