你並不需要使用加入了答案。如果我是你,我會做:
select case when count(*) = 0 then 0
else round(100 * count(case when status not in (0, 1) then 1 end)/count(*), 3)
end non_0_or_1_status_percentage
from o2_cdr_header
where date_created > sysdate - 1;
這裏有一個簡單的演示:
with t as (select 1 status from dual union all
select 2 status from dual union all
select 3 status from dual union all
select 2 status from dual union all
select 4 status from dual union all
select 5 status from dual union all
select 6 status from dual union all
select 7 status from dual union all
select 1 status from dual union all
select 0 status from dual union all
select 1 status from dual)
select case when count(*) = 0 then 0
else round(100 * count(case when status not in (0, 1) then 1 end)/count(*), 3)
end col1
from t
where 1=0;
COL1
----------
0
以防萬一你不知道,這樣做計數的過濾在case語句返回相同的,當你在WHERE子句中過濾器,下面是證明了一個演示它:
with t as (select 1 status from dual union all
select 2 status from dual union all
select 3 status from dual union all
select 2 status from dual union all
select 4 status from dual union all
select 5 status from dual union all
select 6 status from dual union all
select 7 status from dual union all
select 1 status from dual union all
select 0 status from dual union all
select 1 status from dual)
select 'using case statement' how_count_filtered,
count(case when status not in (0, 1) then 1 end) cnt
from t
union all
select 'using where clause' how_count_filtered,
count(*) cnt
from t
where status not in (0, 1);
HOW_COUNT_FILTERED CNT
-------------------- ----------
using case statement 7
using where clause 7
@GordonLinoff'r'在'cross join'之前定義。 – PinnyM
如果您以可讀的方式格式化代碼,將會更容易判斷。 –