SQL用sum函数除以零

时间:2012-06-28 13:50:41

标签: sql sql-server-2008

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

这是SQL:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:4)

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。但这实际上取决于用例。

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

答案 2 :(得分: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