2017-11-04 66 views
-1

表包含50萬行,下面是我正在運行的選擇查詢,但這需要花費很長時間。此查詢是否可以調整?使用UNION使用包含多個SUM()聚合一個查詢使用多個GROUP BY子句調整查詢

select phone_number,rg,val from (
    select phone_number, rg, sum(val) val from 
     (select /*+ PARALLEL(GPRS_CDR 3) */ phone_number, rg1 rg, sum(rg1_vol) val 
      from gprs_cdr 
      where day_of_year=to_char(sysdate -1,'ddd') 
      group by phone_number, rg1 
      union all 
      select /*+ PARALLEL(GPRS_CDR 3) */ phone_number, rg2 rg, sum(rg2_vol) val 
      from gprs_cdr 
      where day_of_year=to_char(sysdate -1,'ddd') 
      group by phone_number, rg2 
      union all 
      select /*+ PARALLEL(GPRS_CDR 3) */ phone_number, rg3 rg, sum(rg3_vol) val 
      from gprs_cdr 
      where day_of_year=to_char(sysdate -1,'ddd') 
      group by phone_number, rg3 
      union all 
      select /*+ PARALLEL(GPRS_CDR 3) */ phone_number, rg4 rg, sum(rg4_vol) val 
      from gprs_cdr 
      where day_of_year=to_char(sysdate -1,'ddd') 
      group by phone_number, rg4 
      union all 
      select /*+ PARALLEL(GPRS_CDR 3) */ phone_number, rg5 rg, sum(rg5_vol) val 
      from gprs_cdr 
      where day_of_year=to_char(sysdate -1,'ddd') 
      group by phone_number, rg5) 
    where rg = '31' 
    group by phone_number,rg 
    order by val desc 
    ) 
where rownum <= 20; 
+0

理智勝出...感謝反諷堆棧 –

+0

顯示錶結構和示例數據。需要檢查'RG2_VOL','RG3_VOL'等包含其他記錄的值。 –

回答

4

重新編寫多個查詢。 UNPIVOT的結果和排序:

SELECT u.* 
FROM (
    SELECT  PHONE_NUMBER 
      ,SUM(CASE WHEN RG1 = '31' THEN RG1_VOL ELSE 0 END) RG1_VAL 
      ,SUM(CASE WHEN RG2 = '31' THEN RG2_VOL ELSE 0 END) RG2_VAL 
      ,SUM(CASE WHEN RG3 = '31' THEN RG3_VOL ELSE 0 END) RG3_VAL 
      ,SUM(CASE WHEN RG4 = '31' THEN RG4_VOL ELSE 0 END) RG4_VAL 
      ,SUM(CASE WHEN RG5 = '31' THEN RG5_VOL ELSE 0 END) RG5_VAL 
    FROM GPRS_CDR 
    WHERE day_of_year=to_char(sysdate -1,'ddd') 
    GROUP BY PHONE_NUMBER 
) 
UNPIVOT (
    Val FOR RG IN ("RG1_VAL", "RG2_VAL", "RG3_VAL", "RG4_VAL", "RG5_VAL") 
) u 
WHERE rownum <= 20 
ORDER BY u.Val DESC