Oracle 使用排名或 dense_rank 重写查询

Oracle rewrite query using rank or dense_rank

我有以下查询和样本数据,工作正常。它找到每个部门员工的最高工资。

虽然它有效,但我喜欢将其更改为使用排名或 dense_rank(不确定如何执行此操作)来实现我在下面生成的输出但是

注意 department_id=1 有 2 名不同的员工领取准确的薪水,我需要保持这样的结果。另外,有没有办法只比较e.department_id = d.department_id一次?

如有任何帮助,我们将不胜感激。下面是我的测试案例和示例数据。


CREATE table dept  (department_id, department_name) AS
SELECT 1, 'IT' FROM DUAL UNION ALL
SELECT 2, 'SALES'  FROM DUAL;

CREATE TABLE employees (employee_id, manager_id, first_name, last_name, department_id, sal,
serial_number) AS
SELECT 1, NULL, 'Alice', 'Abbot', 1, 100000, 'D123' FROM DUAL UNION ALL
SELECT 2, 1, 'Beryl', 'Baron',1, 50000,'D124' FROM DUAL UNION ALL
SELECT 3, 1, 'Carol', 'Chang',1, 100000, 'A1424' FROM DUAL UNION ALL
SELECT 4, 2, 'Debra', 'Dunbar',1, 75000, 'A1425' FROM DUAL UNION ALL
SELECT 5, NULL, 'Emily', 'Eden',2, 90000, 'C1725' FROM DUAL UNION ALL
SELECT 6, 3, 'Fiona', 'Finn',1, 88500,'C1726' FROM DUAL UNION ALL
SELECT 7,5, 'Grace', 'Gelfenbein',2, 55000, 'C1727' FROM DUAL;
 
  select 
    e.employee_id,
    e.first_name,
    e.last_name,
    e.department_id,
    d.department_name,
    e.sal
  from employees e join dept d on e.department_id = d.department_id
    where not exists
      ( select null
        from   employees 
        where  department_id = e.department_id
        and    sal > e.sal );

EMPLOYEE_ID    FIRST_NAME    LAST_NAME    DEPARTMENT_ID    DEPARTMENT_NAME    SAL
1    Alice    Abbot    1    IT    100000
3    Carol    Chang    1    IT    100000
5    Emily    Eden    2    SALES    90000

您可以按如下方式使用RANK

WITH cte AS (
    SELECT e.employee_id, e.first_name, e.last_name, e.department_id,
           d.department_name, e.sal,
           RANK() OVER (PARTITION BY e.department_id ORDER BY e.sal DESC) rnk
    FROM employees e
    INNER JOIN dept d ON e.department_id = d.department_id
)

SELECT employee_id, first_name, last_name, department_id, department_name, sal
FROM cte
WHERE rnk = 1;