求各部门第二高的工资

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

第一步:取出各部门第一高工资的员工的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,即第二高工资

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

附录:各部门的第一高工资以及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
*/

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

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

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

猜你喜欢

转载自my.oschina.net/u/553266/blog/1621440