求各部门第二高的工资

Oracle 查询 EMP 表中各部门工资第二高的信息,注意是各部门,不能指定单个部门sql

第一步:取出各部门第一高工资的员工的empno数据库

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
*/

第二步:取出各部门第一高工资除了上述的empno,即第二高工资spa

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
*/

附录:各部门的第一高工资以及empnocode

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
*/

Oracle数据库中 查询高于本身部门平均工资的员工信息 用相关子查询怎么作啊?

已经有 select a.* from emp a where sal >(select avg(sal) from emp where deptno=a.deptno and__)
and后面是应该加group by deptno 吗?class

答案:不该该加group by deptno。而应该加 deptno=&deptno。该语句会提示用户输入本身的部门编号,以后会进行检索操做返回结果。select

相关文章
相关标签/搜索