[Oracle] efficient SQL statement analysis function (2)-max ()

Source: Internet
Author: User

 

If you want to obtain the employee record with the highest salary for each department, you can use the following four methods:

Create an example table first

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 );

Method 1. Each row in EMP is compared by Max, which takes a long time.

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

Method 2: first query the max Sal and associate it with the EMP table. If the logic is complex, more code is generated.

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

Method 3. Use the max Analysis Function

Select deptno, maxsal, empno from (
Select max (SAL) over (partition by deptno) maxsal, EMP. * from EMP) emp2
Where emp2.sal = emp2.maxsal

Method 4: Use the dense_rank analysis function. If a department may have multiple maximum salaries, you cannot use the row_number () analysis function.

Select deptno, Sal, empno from (
Select EMP. *, dense_rank () over (partition by deptno order by Sal DESC) rownumber from EMP) emp2
Where rownumber = 1

The result is as follows:

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

 

 

 

 

 

 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.