zoukankan      html  css  js  c++  java
  • Oracle update和order by

    今天遇到一个关于SQL转换成Oracle语句的问题,描述如下:

    select * from emp order by deptno;

    select * from dept;

    Sql Server:

    update dept a set dname=(select top 1 ename from emp where deptno=a.deptno order by sal)

    经过尝试,查找资料,得出下面转换结果,不知道这样是否可行:

    update dept a set dname=

    (with t as(select ename,deptno from emp order by sal)

    select ename from t where deptno=a.deptno and rownum=1)

    where exists(with t as(select ename,deptno from emp order by sal)

    select null from t where deptno=a.deptno)

    执行结果:

    select * from dept;

    cost:22

    另外一种:

    update dept a
    set dname =
    (select max(ename)
    from emp
    where deptno = a.deptno
    and sal = (select min(sal) from emp where deptno=a.deptno))
    where exists (select null
    from emp
    where deptno = a.deptno);

    这种耗cost比第一个更大。

    cost:27

    第三种:

    update dept a
    set dname =
    (select col
    from (select decode(row_number()
    over(partition by deptno order by sal),
    1,
    ename,
    null) col,
    deptno
    from emp) b
    where b.deptno = a.deptno
    and b.col is not null)
    where exists (select null from emp where deptno = a.deptno);

    cost:21

    已找到较简洁的方法:

    update dept a
    set dname =
    (select max(ename) keep(dense_rank first order by nvl(sal, 0))
    from emp
    where deptno = a.deptno)
    where exists (select null from emp where deptno = a.deptno);

    cost:18

  • 相关阅读:
    罗马数字
    逆序对
    等价串
    郊区春游
    贝壳找房函数最值
    Educational Codeforces Round 45 Editorial
    Codeforces Round #486 (Div. 3)
    checkbox保存和赋值
    oninput和onchange的区别
    cookie路径概念理解
  • 原文地址:https://www.cnblogs.com/mellowsmile/p/4671464.html
Copyright © 2011-2022 走看看