I have some code made for calculate the average of a row in a table. The problem is now that the sum of MinTwee
, MinEen
, nul
, PlusEen
and PlusTwee
(are column names) is equal to zero, it gives me a divide by zero exception (what is normal of course). How can you protect it that it given't that? I will that if the sum is equal to zero the average is also equal to zero of that row. I use SQL server 2014.
select top 5
id, mintwee, mineen, nul, pluseen, plustwee, naam
from
topic
where
CategorieID = 7 and verwijderd = 0
order by
round(cast((mintwee * (-2) + mineen * (-1) + nul * 0 + pluseen * 1 + PlusTwee * 2) as float) / (MinTwee + MinEen + nul + PlusEen + PlusTwee), 1) desc, creatie desc
You can test for 0 value with a case when
select top 5 id, mintwee, mineen, nul, pluseen, plustwee, naam
from topic
where CategorieID = 7 and verwijderd = 0
order by
case when (MinTwee + MinEen + nul + PlusEen + PlusTwee) = 0 then creatie
else
round(cast((mintwee * (-2) + mineen * (-1) + nul * 0 + pluseen * 1 + PlusTwee * 2) as float) / (MinTwee + MinEen + nul + PlusEen + PlusTwee), 1)
end
desc,
creatie desc