我之前曾问过以下问题:Calculating percentage within the SQL
现在我很幸运能得到一个很好的答案但是在我的问题中我没有考虑到我的行可以包含零。
问题排在哪里简单:
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?
顺便说一下。我们使用的数据库是带有PL SQL的Oracle数据库答案 0 :(得分: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 :(得分:1)
如果除数为零,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;
答案 2 :(得分: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
答案 3 :(得分:1)
据我所知,你的评论中你需要一段时间内接听电话的费率,包括100%来电未接听的天数。
我想最简单的方法是
select sum(number_of_answered) / sum (number_of_calls)
from table
where date between interval_start and interval_end
在这种情况下。