在SQL错误中不能除以零

时间:2012-10-18 16:34:46

标签: sql sql-server-2005

我想知道如果除数= 0,是否有办法不使用除法。在这种情况下,我的查询工作正常,除非它必须除以0.它应该给出答案为0如果除数是0.这有可能吗?这是在SQl 2005中。

谢谢!

Select sum(cast(isnull(S.AmountSold, 0) as numeric(10,2))) As DeliveryTotal,
sum(cast(isnull(S.S_AmountCollected, 0) as numeric(10,2))) as DeliveryTotalCollected
(sum(cast(isnull(S.S_AmountCollected, 0) as numeric(10,2))) / sum(cast(isnull(S.AmountSold, 0) as numeric(10,2))) )*100 as DeliveryTotalPercentageCollected

from Info RD

2 个答案:

答案 0 :(得分:2)

我会使用case when,也许是子查询,以便于阅读......

select DeliveryTotal, DeliveryTotalCollected, 
 case 
   when DeliveryTotalCollected = 0 --if divisor = 0
   then 0 --return 0
   else (DeliveryTotal / DeliveryTotalCollected) * 100 --return division * 100
 end as DeliveryTotalPercentageCollected
from
(Select 
 sum(cast(isnull(S.AmountSold, 0) as numeric(10,2))) As DeliveryTotal,
 sum(cast(isnull(S.S_AmountCollected, 0) as numeric(10,2))) as DeliveryTotalCollected
 from Info RD) as subq

答案 1 :(得分:-1)

查看CASE表达式:

http://msdn.microsoft.com/en-us/library/ms181765.aspx

它允许您在两种情况之间做出决定