Search code examples
sqloracle-databaserownum

How to get two highest salary in emp table?


BREAK ON DEPTNO SKIP 1
compute sum of sal on deptno
 SELECT  deptno, empno, ename,sal FROM
  (SELECT  deptno, empno, ename, sal FROM emp )
  WHERE  EXISTS  (SELECT deptno  FROM dept)     order by 1,2 , sal desc ;

How can I get two highest sal from emp, and what is wrong with my code?


Solution

  • It is not entirely clear what you want. In the title you say "two highest salary", but in the comment you mention something about a sum.

    The following will show the two highest salaries. If there are multiple "highest" salaries, all will be shown

    select deptno, empno, ename, sal
    from (
      SELECT deptno, empno, ename, sal, 
             dense_rank() over (order by sal desc) as rnk
      FROM emp
    ) 
    where rnk <= 2
    order by sal desc;
    

    To get this per department, you can use this:

    select deptno, dept_salary
    from (
      select deptno, dept_salary, 
             dense_rank() over (order by dept_salary desc) as rnk
      from (
        SELECT deptno, sum(sal) as dept_salary
        FROM emp
        group by deptno
      ) t1
    ) t2
    where rnk <= 2
    order by dept_salary desc