使用多个GROUP BY子句调整查询

时间:2017-11-04 06:57:11

标签: sql oracle

表包含5000万行,下面是我正在运行的选择查询,但这需要花费大量时间。可以调整此查询吗?

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;

1 个答案:

答案 0 :(得分:4)

使用UNION重写多个查询,其中一个查询包含多个SUM()聚合。 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