Question

My employees table has 3 columns:

  • emp_id,
  • emp_sal,
  • dept_id.

I need to find, for each department, the employee(s) with the greatest salary. I need to return emp_id, emp_sal and dept_id for those employees.

Thanks in advance

No correct solution

OTHER TIPS

ORACLE supports common table expression and windowing functions,

WITH employees_sal
AS
(
    SELECT  emp_id,
            emp_sal,
            dept_id,
            DENSE_RANK() OVER(PARTITION BY dept_id ORDER BY emp_sal DESC) ranks
    FROM    employee
)
SELECT  emp_id, emp_sal, dept_id
FROM    employees_sal
WHERE   ranks = 1
SELECT EMP_ID,EMP_SAL,DEPT_ID 
FROM EMP
WHERE (DEPT_ID,EMP_SAL) IN (SELECT DEPT_ID,MAX(EMP_SAL) 
                           FROM EMP GROUP BY DEPT_ID)

There's no need to use CTE.

SELECT a.emp_id, a.emp_sal, a.dept_id
FROM employ a
WHERE a.emp_sal = 
    (SELECT MAX(b.emp_sal)
    FROM employ b
    WHERE b.dept_id = a.dept_id
    AND A.emp_id = B.emp_id)
SELECT * FROM 
( 
 SELECT deptno, ename, sal
     , MAX(sal) OVER (PARTITION BY deptno) dept_max_sal 
     , ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY sal desc) rno
   FROM scott.emp 
 )
 WHERE sal = dept_max_sal
  -- AND rno = 1 -- Optional to eliminate same salary employee --
 ORDER BY deptno, sal DESC, ename
/

DEPTNO    ENAME    SAL    DEPT_MAX_SAL    RNO
-----------------------------------------------
10        KING     5000    5000           1
20        FORD     3000    3000           2    -- same sal --
20        SCOTT    3000    3000           1    -- same sal --
30        BLAKE    2850    2850           1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top