this article takes the initial EMP table of SCOTT users as a reference. The code can be used directly.
The statement to query the structure of the EMP table is as follows, code 1:
DESC EMP;
The structure of EMP table is as follows: [result 1]:
SQL> DESC EMP; //Is the name empty? Type ----------------------------------------------------------------- -------- -------------------------------------------- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATE SAL NUMBER(7,2) COMM NUMBER(7,2) DEPTNO NUMBER(2)
.
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP ORDER BY SAL DESC;
The sorting results are as follows, [result 2]:
SQL> SELECT EMPNO,ENAME,SAL,DEPTNO 2 FROM EMP 3 ORDER BY SAL DESC; EMPNO ENAME SAL DEPTNO ---------- ---------- ---------- ---------- 7839 KING 5000 10 7902 FORD 3000 20 7788 SCOTT 3000 20 7566 JONES 2975 20 7698 BLAKE 2850 30 7782 CLARK 2450 10 7499 ALLEN 1600 30 7844 TURNER 1500 30 7934 MILLER 1300 10 7521 WARD 1250 30 7654 MARTIN 1250 30 7876 ADAMS 1100 20 7900 JAMES 950 30 7369 SMITH 800 20 //14 rows selected.
Now I want to find out the highest paid employees in each department. What should I do? Go on...
Method 1 (nested query & max() function & self join)
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP E1 WHERE SAL = ( SELECT MAX(SAL) FROM EMP E2 WHERE E1.DEPTNO=E2.DEPTNO ) ORDER BY DEPTNO;
The query result is as follows, result 3:
SQL> SELECT EMPNO,ENAME,SAL,DEPTNO 2 FROM EMP E1 3 WHERE 4 SAL = ( 5 SELECT MAX(SAL) 6 FROM EMP E2 7 WHERE E1.DEPTNO=E2.DEPTNO 8 ) 9 ORDER BY DEPTNO; EMPNO ENAME SAL DEPTNO ---------- ---------- ---------- ---------- 7839 KING 5000 10 7788 SCOTT 3000 20 7902 FORD 3000 20 7698 BLAKE 2850 30
Method 2 (nested query & rank() function & list partition)
SELECT EMPNO,ENAME,SAL,DEPTNO FROM ( SELECT RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) R, EMPNO,ENAME,SAL,DEPTNO FROM EMP ) WHERE R=1 ORDER BY DEPTNO;
The query result is as follows, result 4:
SQL> SELECT EMPNO,ENAME,SAL,DEPTNO 2 FROM ( 3 SELECT 4 RANK() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) R, 5 EMPNO,ENAME,SAL,DEPTNO 6 FROM EMP 7 ) 8 WHERE R=1 9 ORDER BY DEPTNO; EMPNO ENAME SAL DEPTNO ---------- ---------- ---------- ---------- 7839 KING 5000 10 7788 SCOTT 3000 20 7902 FORD 3000 20 7698 BLAKE 2850 30
Remarks:
- Environment: Windows 10
- Software: Oracle 11g R2.