Oracle queries the information of the second highest salary of each department in the EMP table, note that it is each department, and a single department cannot be specified
Step 1: Take out the empno of the employee with the highest salary in each department
select b.empno from (select deptno,max(sal) sal from emp group by deptno ) a, emp b
where a.deptno=b.deptno and a.sal=b.sal
;
/*
EMPNO
----------
7698
7839
7902
*/
Step 2: Take out the first highest salary in each department except the above empno, that is, the second highest salary
select deptno,max(sal) second_highest from emp
where empno not in(
select b.empno from (select deptno,max(sal) sal from emp group by deptno ) a, emp b
where a.deptno=b.deptno and a.sal=b.sal
)
group by deptno
order by deptno
;
/*
DEPTNO SECOND_HIGHEST
---------- --------------
10 2450
20 2975
30 1600
*/
Appendix: No. 1 highest salary by sector and empno
select b.empno, a.deptno, a.sal from (select deptno,max(sal) sal from emp group by deptno ) a, emp b
where a.deptno=b.deptno and a.sal=b.sal
order by a.deptno
;
/*
EMPNO DEPTNO SAL
---------- ---------- ----------
7839 10 5000
7902 20 3000
7698 30 2850
*/
How to use correlated subquery to query employee information with higher salary than the average salary of your own department in Oracle database?
There is already select a.* from emp a where sal >(select avg(sal) from emp where deptno=a.deptno and__)
and should be followed by group by deptno?
Answer: group by deptno should not be added. Instead, deptno=&deptno should be added. The statement will prompt the user to enter their department number, and then the retrieval operation will be performed to return the result.