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