ITPUB上一个Oracle面试题

1,select a.deptno,a.ename,a.sal from  scott.emp a,
(select deptno,max(sal) max_sal from scott.emp group by deptno ) b where a.sal=b.max_sal  and a.deptno=b.deptno order by sal desc
2,select deptno,ename,sal from
     (select deptno,ename,sal,rank() over (partition by deptno order by sal desc) as sal_order
         from scott.emp) where sal_order <2
  问:这两条语句的2效率为什么比1高?

因为(2)对emp表只访问了一次, 而(1)却访问了二次, 故(2)的consistent gets的数量比(1)要小的多, 因此(2)的语句执行效率要更高的多。
这个问题我之前就回答过了, 你可以去看看!

关于排序的话, 这里的2个语句都会有一个"1 sort (memory)", 只是, 语句(1)使用的是sort group by, 而语句(2)使用的是window sort!

window sort

--分析函数中一般都有partition by的关键字将数据分成一个个小的区(PARTITION)也叫做WINDOW, 因为分区的过程中已经有ORDER BY的操作,所以每个WINDOW中的数据也就已经SORT了, 所以你会看到WINDOW SORT. 这种分析函数效率是非常高的,因为它只需一次排序操作就完成所有分区内相关的计算, 或者中N个分析函数都在一次排序中完成。

原文地址:https://www.cnblogs.com/tracy/p/1940271.html