我的员工表有 3 列:
emp_id
,emp_sal
,dept_id
.
我需要为每个部门找到薪水最高的员工。我需要返回emp_id
,emp_sal
并dept_id
为那些员工。
提前致谢
我的员工表有 3 列:
emp_id
,emp_sal
,dept_id
.我需要为每个部门找到薪水最高的员工。我需要返回emp_id
,emp_sal
并dept_id
为那些员工。
提前致谢
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
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)
无需使用 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