现有表A,B结构如下:
A                                    B 
NAME   PAY_NO    DATE             PAY_NO    TYPE  FEE
aa       01     2013-08-01         01       一级  10.1
bb       02     2013-07-30         01       二级  20.1
cc       03     2013-07-20         03       一级  33.3
cc       04     2013-05-20         04       三级  21.1
A主表,B子表;
现须查A中DATE 几个月中NAME总数、以及产生的Fee总和;
提示:A中7、8月的数据行约5W条,每一条A记录对应B费用记录约4条;
现有语句:
1、用left join
select count(tt.name),sum(tt.fee) from 
(
select a.name,sum(nvl(b.fee,0)) fee
from a left join b on a.pay_no = b.pay_no 
where to_char(a.date,'yyyyMM')>='201307' and to_char(a.date,'yyyyMM')<='201308' 
group by a.name) tt;
2、使用方法取费用
select count(tt.name),sum(tt.fee) from 
(
select a.name, 方法1(a.pay_no)fee
from a 
 where to_char(a.date,'yyyyMM')>='201307' and to_char(a.date,'yyyyMM')<='201308'
) tt; 方法1 为根据PAY_NO到B中取费用和;以上两种方法耗时都挺长,需4到5分钟,求优化或思路,谢谢!
 
SQL性能优化行业数据select

解决方案 »

  1.   

    date字段建立索引
    并把sql改为select count(tt.name), sum(tt.fee)
      from (select a.name, sum(nvl(b.fee, 0)) fee
              from a
              left join b
                on a.pay_no = b.pay_no
             where a.date >= to_date('201307' || '01', 'yyyymmdd')
               and a.date <= to_date('201308' || '01', 'yyyymmdd')
             group by a.name) tt;
      

  2.   


      and a.date <= to_date('201308' || '01', 'yyyymmdd')
    应该是
      and a.date < to_date('201309' || '01', 'yyyymmdd')
      

  3.   


      and a.date <= to_date('201308' || '01', 'yyyymmdd')
    应该是
      and a.date < to_date('201309' || '01', 'yyyymmdd')date 已有索引,不晓得加到天有神马意义呢?
      

  4.   


      and a.date <= to_date('201308' || '01', 'yyyymmdd')
    应该是
      and a.date < to_date('201309' || '01', 'yyyymmdd')date 已有索引,不晓得加到天有神马意义呢?你可以看看索引的用法。如果把函数用到索引字段上,是不走索引的。他这方法应该可以改善你的sql的。