[Oracle]高效的SQL語句之分析函數(二)–max()

來源:互聯網
上載者:User

 

如果我們按照樣本想得到每個部門薪水值最高的僱員的紀錄,可以有四種方法實現:

先建立樣本表

create table emp
as
select * from scott.emp;

alter table emp
add constraint emp_pk
primary key(empno);

create table dept
as
select * from scott.dept;

alter table dept
add constraint dept_pk
primary key(deptno);

方法1.emp中的每一行都會進行max比較,費時

select * from emp emp1 where emp1.sal=(select max(emp2.sal) from emp emp2 where emp2.deptno=emp1.deptno)

方法2.先子查詢尋找出max sal,然後與emp表相關聯,如果邏輯複雜會產生較多代碼

   select * from emp emp1,(select deptno,max(sal) maxsal from emp emp2 group by emp2.deptno) emp3 where emp1.deptno=emp3.deptno and emp1.sal=emp3.maxsal

方法3.使用max分析函數

select deptno,maxsal,empno from(
 select max(sal) over (partition by deptno) maxsal,emp.* from emp) emp2
 where emp2.sal=emp2.maxsal

方法4.使用dense_rank分析函數,如果一個部門可能存在多筆最大薪水,就不能使用row_number()分析函數

select deptno,sal,empno from( 
 select emp.*,DENSE_RANK() over (partition by deptno order by sal desc) rownumber from emp) emp2
 where rownumber=1 

結果如下:

10    5000.00    7839
20    3000.00    7788
20    3000.00    7902
30    2850.00    7698

 

 

 

 

 

 

 

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.