Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL divide by zero with a sum function

I am having problems with dividing by zero. If the denominator is zero I would like the value to be zero. When I try using nullif, I end up with a zero or one for the calculated value.

Here is the SQL:

Select 
    StateCode, Month1Date,(Sum(Order)/Sum(Value)) as myValue    
from tblOrders    
     inner join tblStates on OrderStateCode = StateCode    
group by StateCode, Month1Date
like image 579
Mike Avatar asked Jun 28 '12 13:06

Mike


2 Answers

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

A 0 denominator is changed to NULL, which will cause the result to be NULL. The whole result then has ISNULL() to turn any NULLs to 0's.

Personally I would not include the ISNULL() and leave the result as NULL. But it depends on use-case really.

EDIT: Deleted the CASE WHEN version as another answer had it just before mine.

like image 170
MatBailie Avatar answered Sep 19 '22 22:09

MatBailie


You need a case statement:

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
like image 29
Gordon Linoff Avatar answered Sep 18 '22 22:09

Gordon Linoff