3

我有以下代码:

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"被激活。

4

4 回答 4

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
于 2013-07-24T09:34:44.240 回答
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

SQLFiddle示例

于 2013-07-24T09:31:05.000 回答
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]
于 2013-07-24T09:41:34.350 回答
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
于 2013-07-24T09:32:50.467 回答