从两个SQL查询的数值结果计算百分比的更好方法是什么

时间:2017-08-09 19:07:30

标签: oracle11g

我有两个oracle(11g)SQL查询,每个查询都会给出一个数字结果。

SQL1:

select count(*) as count1 
  from table_name1
 where col1_number in (2400)
   and (col2_varchar2 = '' or col2_varchar2 is null or col2_varchar2 = 'BLANK' or 
        col2_varchar2 = 'TBA' or col2_varchar2 like 'B%')
   and col3_varchar2 = 'app31'
   and col4_date > (sysdate - 7)

SQL2:

select count(*) as count2 
  from table_name1
 where col1_number in (2400)
   and col3_varchar2 = 'app31'
   and col4_date > (sysdate - 7)

假设我从SQL1得到35,结果得到SQL2得到831。然后我想编写一个SQL,它将从SQL1和SQL2中获取这两个结果并计算(35 * 100)/ 831。

我已经编写了一个可以执行此操作的SQL。

SQL3:

select round((count1 * 100)/count2,3) as percent_missing from
(
with temp_table1 as (
    select count(*) as count1 
      from table_name1
     where col1_number in (2400)
       and (col2_varchar2 = '' or col2_varchar2 is null or col2_varchar2 = 
            'BLANK' or col2_varchar2 = 'TBA' or col2_varchar2 like 'B%')
       and col3_varchar2 = 'app31'
       and col4_date > (sysdate - 7)
), 

temp_table2 as (
    select count(*) as count2 
      from table_name1
     where col1_number in (2400)
       and col3_varchar2 = 'app31'
       and col4_date > (sysdate - 7)
) 
select count1, count2 
  from temp_table1, temp_table2
);

问题:有没有更好的方法呢?我想知道在这种情况下是否还有其他/更好的方法。

1 个答案:

答案 0 :(得分:1)

我可以看到SQL1和SQL2使用相同的表和几乎相同的where子句,除了SQL1中的额外AND条件,那么为什么我们不要像下面那样合并它们:

select round((a.count1 * 100)/a.count2,3) as percent_missing from (
    select count(case when (col2_varchar2 = '' or col2_varchar2 is null or col2_varchar2 = 
                'BLANK' or col2_varchar2 = 'TBA' or col2_varchar2 like 'B%') then 1 end ) as count1, 
                count(1) as count2 
            from table_name1 where
                col1_number in (2400) and 
                and col3_varchar2 = 'app31'
                and col4_date > (sysdate - 7)
    ) as a

我无法测试这个,因为我没有表和他们的架构请原谅我编译错误,但你会在这里得到想法。