SQL 服务器中连续列的平均值除以零异常

Divide by zero exception of average of columns in a row in SQL Server

我编写了一些代码来计算 table 中一行的平均值。现在的问题是 MinTweeMinEennulPlusEenPlusTwee (是列名) 等于零,它给了我一个除以零的异常 (当然是正常的)。你怎么能保护它不给它呢?我会认为,如果总和等于零,则该行的平均值也等于零。我使用 SQL 服务器 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 值
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

我认为避免错误的最简单方法是 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