0

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

APC
  • 144,005
  • 19
  • 170
  • 281

4 Answers4

4

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
John Woo
  • 258,903
  • 69
  • 498
  • 492
3
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)
APC
  • 144,005
  • 19
  • 170
  • 281
Aspirant
  • 2,238
  • 9
  • 31
  • 43
2

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)
David R.
  • 281
  • 2
  • 14
  • Equally, there's no need to use a correlated subquery either. Both methods are fine. – David Aldridge Mar 11 '13 at 07:22
  • Judging by the reputation of the asker, I just wanted to use something they would likely be able to understand easier than learning CTE. This query is common practice in Oracle DB for PeopleSoft, so it's likely to be seen in other code you interact with. – David R. Mar 11 '13 at 12:31
  • This query returns the employees whose salary matches a maximum departmental salary. It does not return the employees who are the highest paid in each department. – APC Mar 11 '13 at 20:18
  • Good call, I left off a line. This is extremely similar to code I use every single day. – David R. Mar 11 '13 at 21:12
0
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
Art
  • 5,616
  • 1
  • 20
  • 22