0

我想知道如果除数 = 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
4

2 回答 2

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
于 2012-10-18T16:39:08.273 回答
-1

查看 CASE 表达式:

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

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

于 2012-10-18T16:37:18.193 回答