划分两个复杂的列(Oracle)

时间:2014-10-01 14:43:12

标签: oracle math

我从我们的Oracle数据库中提取统计数据。这个查询...

select
    substr(cm.course_name,0,INSTR(cm.course_name,'.',1,1) - 1) as "SUBJECT",
      count(*) as "TOTAL SHELLS",    
      count(case when (cs.size_total = 0 or cm.pk1 not in (select crsmain_pk1 from course_size))
          and not exists (select 1 from course_contents where crsmain_pk1 = cm.pk1)
      then 1 else null end) as "EMPTY SHELLS",     
    from course_main cm
    left join course_size cs on cm.pk1 = cs.crsmain_pk1
    where cm.row_status = 0
    and cm.data_src_pk1 in (select pk1 from data_source where batch_uid like ('%2014FA'))
    group by substr(cm.course_name,0,INSTR(cm.course_name,'.',1,1) - 1);

...生成此结果:

--SUBJECT, TOTAL SHELLS, EMPTY SHELLS
--DHY, 40, 19
--HSC, 10, 0
--BIO, 79, 7

虽然这个结果是可用的,但我想在最后两列之间计算百分比,所以我得到的结果如下:

--SUBJECT, TOTAL SHELLS, EMPTY SHELLS, % EMPTY
--DHY, 40, 19, 48%
--HSC, 10, 0, 0%
--BIO, 79, 7, 9%

执行此操作的唯一方法AFAIK是复制每个count语句并将它们用作分子和分母,但这意味着不必要地重新计算我们已经拥有的两个值 - 更不用说使查询变得笨重而且难以阅读。还有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

只需将您的查询用作子查询,以避免重新计算所有。

SELECT 
subject as "SUBJECT", 
totalshells as "TOTAL SHELLS", 
emptyshells as "EMPTY SHELLS", 
ROUND((emptyshells / totalshells) * 100) as "% EMPTY"
from
(select
    substr(cm.course_name,0,INSTR(cm.course_name,'.',1,1) - 1) as subject,
      count(*) as totalshells,    
      count(case when (cs.size_total = 0 or cm.pk1 not in (select crsmain_pk1 from course_size))
          and not exists (select 1 from course_contents where crsmain_pk1 = cm.pk1)
      then 1 else null end) as emptyshells,     
    from course_main cm
    left join course_size cs on cm.pk1 = cs.crsmain_pk1
    where cm.row_status = 0
    and cm.data_src_pk1 in (select pk1 from data_source where batch_uid like ('%2014FA'))
    group by substr(cm.course_name,0,INSTR(cm.course_name,'.',1,1) - 1)) s