2

我之前问过以下问题:Calculating percent 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 数据库

4

4 回答 4

3
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
于 2012-12-07T12:58:15.990 回答
3

如果除数为零,则该nullif函数可用于返回 null。当 SQL 遇到空除数时,它会强制整个等式返回空值,从而防止发生错误。

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;
于 2012-12-07T12:59:04.273 回答
2

我认为您的意思是“Number_Of_Calls”可能为零(从而引发 zero_divide 错误?)如果是这样

case Number_Of_Calls when 0 then 0 else ((Number_of_answered/Number_Of_Calls)*100) as answer_percent
于 2012-12-07T13:00:42.573 回答
2

据我从您的评论中了解到,您想要一段时间内的接听电话率,包括 100% 电话无人接听的日子。

我想最简单的方法是

select sum(number_of_answered) / sum (number_of_calls) 
  from table 
 where date between interval_start and interval_end

在这种情况下。

于 2012-12-07T13:35:29.680 回答