2017-08-09 33 views
0

我有兩個oracle(11g)SQL查詢,每個查詢都給出一個數字結果。什麼是從兩個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) 

可以說,我得到35從SQL1結果和831從SQL2結果。然後我想編寫一個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

我可以看到兩個SQL1和SQL2使用相同的表和幾乎相同的地方除了在SQL1一個額外的條件子句,以便我們爲什麼不只是鞏固他們象下面這樣:

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 

我無法測試這個因爲我沒有表格和他們的模式,請原諒我的編譯錯誤,但你會在這裏想法。

+0

感謝您的回覆,刪除重複的「and」和「as」後,您建議的SQL與SQL3的工作方式相同。它看起來更乾淨,所以我打算使用這個版本。 – 300