• 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

  • 相关阅读:
    HDOJ_ACM_超级楼梯
    HDOJ_ACM_下沙的沙子有几粒?
    杭电_ACM_How Many Trees
    HDOJ_ACM_Tiling_easy version
    HDOJ_ACM_母牛的故事
    HDOJ_ACM_小兔的棋盘
    HDOJ_ACM_一只小蜜蜂
    杭电_ACM_Count the Trees
    HDOJ_ACM_折线分割平面
    Sun Solaris下JAVA以及JSP开发环境的配制小记
  • 原文地址:https://www.cnblogs.com/mellowsmile/p/4671464.html
Copyright © 2020-2023  润新知