0

我的员工表有 3 列:

  • emp_id,
  • emp_sal,
  • dept_id.

我需要为每个部门找到薪水最高的员工。我需要返回emp_idemp_saldept_id为那些员工。

提前致谢

4

4 回答 4

4

ORACLE支持常用的表表达式和窗口函数,

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
于 2013-03-11T02:18:38.113 回答
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)
于 2013-03-11T02:23:10.673 回答
2

无需使用 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)
于 2013-03-11T02:20:40.007 回答
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
于 2013-03-11T18:46:50.080 回答