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 */
已經有 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