6

我在除以零时遇到问题。如果分母为零,我希望该值为零。当我尝试使用nullif时,我最终得到一个零或一作为计算值。

这是SQL:

Select 
    StateCode, Month1Date,(Sum(Order)/Sum(Value)) as myValue    
from tblOrders    
     inner join tblStates on OrderStateCode = StateCode    
group by StateCode, Month1Date
4

3 回答 3

7
Select
  StateCode,
  Month1Date,
  ISNULL(Sum(Order) / NULLIF(Sum(Value), 0), 0) AS myValue
from
  tblOrders
inner join
  tblStates
    on OrderStateCode = StateCode
group by
  StateCode,
  Month1Date

0分母更改为NULL,这将导致resultNULL。然后整个结果必须ISNULL()将任何 NULL 变为 0。

就我个人而言,我不会包含ISNULL()并将结果保留为NULL. 但这实际上取决于用例。

编辑:删除了 CASE WHEN 版本,因为另一个答案就在我之前。

于 2012-06-28T13:52:49.420 回答
5

你需要一个案例陈述:

Select StateCode, Month1Date,
        (case when sum(value) = 0 then 0 else Sum(Order)/Sum(Value)
         end) as myValue
from tblOrders inner join
     tblStates
     on OrderStateCode = StateCode
group by StateCode, Month1Date
于 2012-06-28T13:52:41.730 回答
0

试试这个。

SELECT StateCode, Month1Date,
        CASE WHEN SUM(Value) <> 0 THEN(SUM(Order)/SUM(Value))
        ELSE 0 END as myValue
    FROM tblOrders 
    INNER JOIN tblStates ON OrderStateCode = StateCode 
    GROUP BY StateCode, Month1Date
于 2012-06-28T14:11:33.930 回答