Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
SELECT Sum(DailySum)as DailySum, sum(Unified) as Unified,
(Sum(DailySum)/sum(Unified)) AS HPPL
FROM ProductionEntry

Here in database the value of Unified is 0. As a result when Unified is trying to divide DailySum then it arises error. Both of the field's datatype are decimal. Please help me.
Posted

There is few ways at least to avoid 'divide by zero' error.
1) NULLIF[^] function - zero is replaced with NULL. Any operation on NULL returns NULL always ;)
SQL
SELECT Field1, Field2, Field1/NULLIF(Field2,0) AS Result
FROM TableName


2) CASE ... END[^] statement - returns divide result only for non-zero values
SQL
SELECT Field1, Field2, CASE WHEN Field2 = 0 THEN 0 ELSE Field1/Field2 END AS Result
FROM TableName


3) WHERE[^] clause - returns non-zero values in subquery; note: Field2 data equal to zero are ignored!
SQL
SELECT Field1, Field2, Field1/Field2 AS Result
FROM (
    SELECT Field1, Field2
    FROM TableName
    WHERE Field2>0
) AS A
 
Share this answer
 
v3
Comments
Abhinav S 24-Feb-14 6:35am    
5!
Maciej Los 24-Feb-14 6:44am    
Thank you ;)
as you mention that, Unified is 0 and you are trying to use it with divide operation then it will giving you error because we can not divide any value with 0. in the same way if you divide any value with 1 then you got answer as the same value, so in your case you can use this type of query...

SQL
SELECT
    SUM(DailySum)as DailySum
    ,SUM(Unified) as Unified
    ,(SUM(DailySum)/
        CASE WHEN SUM(Unified) > 0 THEN SUM(Unified) ELSE 1 END
    ) AS HPPL
FROM ProductionEntry


I have checked that, if Sum of Unified is 0 then it will replace with 1 or if it is more then 0 then it will use actual value
 
Share this answer
 
Comments
Maciej Los 24-Feb-14 6:27am    
In my opinion - partial answer, +4,!
Please see my solution.
Change your query slightly by putting a case statement.

SQL
SELECT Sum(DailySum)as DailySum, sum(Unified) as Unified,
case when sum(Unified) != 0 (Sum(DailySum)/sum(Unified)) else 'NA' end AS HPPL
FROM ProductionEntry


NA is not applicable for cases when sum of unified is 0.
 
Share this answer
 
Comments
Maciej Los 24-Feb-14 6:27am    
In my opinion - partial answer, +4!
Please see my solution.
Abhinav S 24-Feb-14 6:35am    
Thank you.
a better way would be to do (SUM(DailySum)/ NULLIF(SUM(Unified), 0))
 
Share this answer
 
Comments
Maciej Los 24-Feb-14 6:27am    
In my opinion - partial answer, +4!
Please see my solution.
db7uk 24-Feb-14 6:51am    
Yep completely agree. The solution you provided was better in terms of coverage.
Maciej Los 24-Feb-14 7:08am    
Thank you ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900