zoukankan      html  css  js  c++  java
  • Oracle Sql优化之Merge 改写优化Update

    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)
  • 相关阅读:
    c# 反射应用之工厂
    UnityContainer 实现DI
    TinyMCE 的音乐插件/mp3 music insert plugin
    Django on IronPython and Windows
    说说分页
    Katze 简单的.net "ORM"框架
    Discuz!NT在64位Windows下运行的问题
    恐怖的迅雷
    基于Gettext的asp.net网站多语言解决方案
    微软是如何输掉API之战(下)
  • 原文地址:https://www.cnblogs.com/zhulongchao/p/4572697.html
Copyright © 2011-2022 走看看