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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM