我有一些代码用于计算表中行的平均值。问题是,MinTwee
,MinEen
,nul
,PlusEen
和PlusTwee
(列名称)的总和是等于零,它给我一个除零异常(当然是正常的)。你怎么能保护它不给它呢?我想如果总和等于零,那么平均值也等于该行的零。我使用的是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
答案 0 :(得分:3)
您可以使用
时的情况测试0值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
答案 1 :(得分:1)
我认为避免错误的最简单方法是nullif()
:
order by
coalesce(round(cast((mintwee * (-2) + mineen * (-1) + nul * 0 + pluseen * 1 + PlusTwee * 2) as float) /
nullif(MinTwee + MinEen + nul + PlusEen + PlusTwee, 0), 1), 0) desc,
creatie desc