码迷,mamicode.com
首页 > 数据库 > 详细

Oracle Sql优化之Merge 改写优化Update

时间:2015-06-12 23:50:37      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

1.待改写语句如下

update table1 f 
set f.ljjine1= (select nvl(sum(nvl(b.jine1,0)),0) from table1 b where b.kjqj<=f.kjqj and b.gs=f.gs and        b.bm=f.bm and b.yw=f.yw and b.currency=f.currency and substr(b.kjqj,1,4)=substr(f.kjqj,1,4)),
f.jine2  = (select nvl(sum(nvl(e.jine1,0)),0) from table2 e where e.kjqj=f.kjqj=e.gs=f.gs and e.bm=f.bm and e.yw= f.yw),
f.ljjine2 = (select nvl(sum(nvl(e.jine1,0)),0) from table2 e where e.kjqj<=f.kjqj and e.gs=f.gs and   e.bm=f.bm and e.yw=f.yw  and substr(e.kjqj,1,4)=substr(f.kjqj,1,4))
where substr(f.kjqj,1,4)= extract(year from sysdate)

2.分析语句:

a.第一个子查询除了等值条件,还有一个 “b.kjqj<=f.kjqj”非等值比较,因此这是一个累加,需要采用分析函数

b.第二个子查询有sum聚合函数,因此要把关联条件放入group by中,分组汇总

c.第三个子查询与第二个类似,只是等值条件改成不等值条件,所以要采用分析函数

3.子查询改写

第一个子查询改写如下

select b.rowid as rid ,sum(b.jine1) over (partition by b.gs,b.bm,b.yw,b.curreny order by b.kjqj) as ljjine1 
from table1 b where substr(b.kjqj,1,4) = extract(year from sysdate)

第二个子查询改写,把关联列放到Select和group by后面

select e.gs,e.bm,e.yw,e.kjqj,sum(jine1) as jine2 
from table2 e
where substr(e.kjqj,1,4)=extract(year from sysdate)
group by e.gs,e.bm,e.yw,e.kjqj

第三个子查询,可以在第二次子查询的基础上调用一次分析函数进行累加处理

select e.gs,e.bm,e.yw,e.kjqj,
sum(e.jine2) over(partition by e.gs,e.bm,e.yw order by e.kjqj) as ljjine2
from
 (select e.gs,e.bm,e.yw,e.kjqj,sum(jine1) as jine2 
from table2 e
where substr(e.kjqj,1,4)=extract(year from sysdate)
group by e.gs,e.bm,e.yw,e.kjqj) e

4.Merge改写的最终结果如下

Merge into table1 f
using(select b.rowid as rid ,sum(b.jine1) over (partition by b.gs,b.bm,b.yw,b.curreny order by b.kjqj) as ljjine1 
from table1 b  left join (
    select e.gs,e.bm,e.yw,e.kjqj,
   sum(e.jine2) over(partition by e.gs,e.bm,e.yw order by e.kjqj) as ljjine2
  from
   (select e.gs,e.bm,e.yw,e.kjqj,sum(jine1) as jine2 
   from table2 e
   where substr(e.kjqj,1,4)=extract(year from sysdate)
   group by e.gs,e.bm,e.yw,e.kjqj) e
) e on(b.gs=e.gs and b.bm=e.bm and b.yw=e.yw and b.kjqj=e.kjqj)
where substr(b.kjqj,1,4) = extract(year from sysdate)) b on (f.rowid=b.rid)
when matched then
   update set
    f.ljjine1= nvl(b.ljjine1,0),
    f.ljjine2=nvl(b.ljjine2,0),
    f.jine2 = nvl(b.jine2,,0)

Oracle Sql优化之Merge 改写优化Update

标签:

原文地址:http://www.cnblogs.com/zhulongchao/p/4572697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!