Divide by Zero Error Encountered when using multiple SUM

982 views Asked by At

I have created the following query

SELECT LPORGNAME
,SUM(TOTALNoOFTRANSFERS) as TOTAL
,SUM(TReads) AS TReads
,ISNULL(ROUND(ISNULL(SUM(TReads),0)/CAST(SUM(TOTALNoOFTRANSFERS)AS FLOAT)*100,2),0)
FROM T_SPID_TRANSFER_IVSO
WHERE DM_FISC_YEAR = '2014-15'
GROUP BY LPORGNAME, DM_FISC_YEAR
ORDER BY LPORGNAME, DM_FISC_YEAR

But I am running into the divieded by zero error, as you can see i have tried to attempt a ISNULL way, but this doesnt work. How would i go about fixing this?

EDIT The TOTALNoOFTRANSFERS is a SUM Column that does not allow NULLS so there for it will always be 0

EDIT Found a simple way to avoid all the 0's. Adding an WHERE TOTALNoOFTRANSFERS > 0, avoids all the 0's all together

1

There are 1 answers

0
juergen d On

Basically you do

SUM(TReads) / SUM(TOTALNoOFTRANSFERS)*100

which could be for instance

3 / 0

Dividing by zero can't be calculated. Think about what should be displayed then and make an exception. Like this

case when SUM(TOTALNoOFTRANSFERS) = 0
     then 0
     else SUM(TReads) / SUM(TOTALNoOFTRANSFERS)*100
end