2012-12-07 93 views
1

計算百分比我以前提出以下問題:Calculating percentage within the SQL當行可以包含0

現在,我很幸運,在我的問題我沒有考慮到我行可能包含零但是得到一個偉大的答案。

的問題,排在那裏簡單:

select 
Number_of_Calls, 
Number_of_Answered, 
((Number_of_answered/Number_Of_Calls)*100) as answer_percent, 
Date 
from table Where Date BETWEEN '2012-09-10' AND '2012-09-11' 

然而Number_of_answered可能是零(如果公司沒有接聽電話),所以如果我想在個完整的電話號碼我如何採取0到帳戶?

順便說一句。我們使用的數據庫是SQL PL

+0

添加到「AND Number_of_answered> 0」? – Kosta

+0

如果您的答案數量爲零,那麼您的答案百分比爲零,那有什麼問題? –

+0

@beherenow其實我的聲明中有一個錯誤,它假設爲Number_of_calls/Number_of_answered –

回答

1

Oracle數據庫的nullif功能可用於返回null如果除數爲零。當SQL遇到空分隔符時,它會強制整個方程返回null,從而防止發生錯誤。

select 
Number_of_Calls, 
Number_of_Answered, 
((Number_of_answered/nullif(Number_Of_Calls,0))*100) as answer_percent, 
Date 
from table Where Date BETWEEN '2012-09-10' AND '2012-09-11' 

如果你想排除空比例使用下面的SQL:

select * from(select 
    Number_of_Calls, 
    Number_of_Answered, 
    ((Number_of_answered/nullif(Number_Of_Calls,0))*100) as answer_percent, 
    Date 
    from table Where Date BETWEEN '2012-09-10' AND '2012-09-11') alias 
where answer_percent is not null; 
+0

當我寫這個時,我得到S1000(906)[Oracle] [ODBC] [Ora] ORA-00906:丟失左括號 –

+0

您是否複製並粘貼或轉錄答案?轉錄的意思輸入在?我沒有看到任何語法問題,可以在我的db上執行類似的語句。 –

+0

這是我在我的數據庫語句:選擇 ANTAL_KALD, BESVARET_25_SEK, ((ANTAL_KALD/NULLIF(BESVARET_25_SEK,0))* 100)answer_percent, TIDSPUNKT 從表在哪裏TIDSPUNKT BETWEEN '2012年9月10日' AND '2012-09-11' –

2
Case when Number_Of_Calls = 0 
    THEN 0 --or your desired value, maybe 100 
    else (Number_of_answered/Number_Of_Calls)*100 
END as answer_percent 
1

我想你的意思是「Number_Of_Calls」可能是零(從而提高一個ZERO_DIVIDE誤差?)如果是這樣做

case Number_Of_Calls when 0 then 0 else ((Number_of_answered/Number_Of_Calls)*100) as answer_percent 
1

據我瞭解你的評論,你希望在一段時間內接聽電話的比率,包括100%電話沒有答案的時間。

我猜simpliest的做法是

select sum(number_of_answered)/sum (number_of_calls) 
    from table 
where date between interval_start and interval_end 
在這種情況下