2012-10-18 24 views
0

我想知道是否有一種方法,如果除數= 0不使用除法。在這種情況下,我有查詢工作正常,除非它必須除以0。如果除數爲0,它應該給出答案爲0。是否有可能?這是在SQl 2005.SQL中不能被零除錯誤

謝謝!

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 
+0

你應該可以使用'case' func這就像一個三元操作:「選擇column1,case'column2'當'Y'然後'abc'else'xyz'從table1結束column2' – ChrisW

+0

我錯過了顯示0的位。我刪除了我的答案:) – SchmitzIT

+0

use一個案例..當時聲明 –

回答

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

查找到CASE表達式:

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

它可以讓你在兩種情況之間決定

+0

調查CASE與一個非現場位置的鏈接不是一個答案。發表一個使用它的例子;沒有這些,這是屬於該問題的評論。 –

+0

@Ken White:謝謝你指出我錯誤地使用了StackOverflow。我非常渴望學習正確的方法,所以你能否指出我可以接受的答案的文檔中的特定章節/文章?謝謝 –

+0

@mrlucmorin - 你可以去這裏(http://stackoverflow.com/faq#deletion)和這裏(http://stackoverflow.com/questions/how-to-answer) – Lamak