oracle 你将如何从每个部门中找到薪水最高的第三名员工[重复]

rdrgkggo  于 2023-08-03  发布在  Oracle
关注(0)|答案(2)|浏览(112)

此问题在此处已有答案

Second highest grade for each student(3个答案)
Select First Row of Every Group in sql [duplicate](2个答案)
3天前关闭。
你如何在Oracle SQL中找到每个部门工资最高的第三个员工?

Select * 
from 
    (select 
         emp-id, dept_id, 
         row_number (order by salary desc) rn 
     from 
         employee 
     group by 
         emp_id, dept_id, salary) 
where rn = 3

字符串

8yparm6h

8yparm6h1#

您提供的SQL查询看起来几乎是准确的,但是有几个问题。GROUP BY子句是不必要的,您必须分别考虑每个部门内的级别(rn)。您可以通过在ROW_NUMBER()函数中使用PARTITION BY子句沿着ORDER BY子句来实现这一点。下面是更正后的SQL查询:

SELECT *
FROM (
    SELECT
        emp_id,
        dept_id,
        salary,
        ROW_NUMBER() OVER (PARTITIONED BY dept_id ORDER BY salary DESC) AS rn
    FROM
        employee
) ranked_employee
WHERE rn = 3;

字符串
在这个查询中,ROW_NUMBER()函数根据薪水的降序为每个部门中的每一行生成一个唯一的等级。PARTITIONED BY dept_id可确保为每个部门单独进行排名。然后,在外部查询中,我们选择rank(rn)等于3的行,这对应于每个部门中工资最高的第三个员工。

iklwldmw

iklwldmw2#

使用分析RANK或DENSE_RANK函数,具体取决于您要如何处理关系。

CREATE TABLE departments(  department_id, department_name) AS
SELECT 1, 'IT' FROM DUAL UNION ALL
SELECT 2, 'Sales' FROM DUAL UNION ALL
SELECT 3, 'Marketing' FROM DUAL UNION ALL
SELECT 4, 'Finance' FROM DUAL;

CREATE TABLE employees (employee_id, first_name, last_name, hire_date, salary,  department_id) AS
SELECT 1, 'Lisa', 'Saladino', DATE '2001-04-03', 160000, 1 FROM DUAL UNION ALL
SELECT 2, 'Sandy', 'Herring', DATE '2011-08-04', 150200, 1 FROM DUAL UNION ALL
SELECT 3, 'Beth', 'Cooper', DATE '2019-03-05', 60700, 1 FROM DUAL UNION ALL
SELECT 4, 'Carol', 'Orr', DATE '2007-11-11', 70125,1 FROM DUAL UNION ALL
SELECT 5, 'Vicky', 'Palazzo', DATE '2004-09-17', 68525,2 FROM DUAL UNION ALL
SELECT 6, 'Cheryl', 'Ford', DATE '2020-05-10', 110000,1 FROM DUAL UNION ALL
SELECT 7, 'Leslee', 'Altman', DATE '2008-12-10', 66666, 1 FROM DUAL UNION ALL
SELECT 8, 'Jill', 'Coralnick', DATE '2001-04-11', 190000, 2 FROM DUAL UNION ALL
SELECT 9, 'Faith', 'Aaron', DATE '2001-04-17', 122000,2 FROM DUAL UNION ALL
SELECT 10, 'Silvio', 'Dante', DATE '2022-10-16', 102150,4 FROM DUAL UNION ALL
SELECT 11, 'Jerry', 'Torchiano', DATE '2022-10-30', 112660,4 FROM DUAL;

select  rnk, last_name, department_id, salary 
from    (
    select  last_name, department_id, salary,
        RANK () OVER ( PARTITION BY  department_id
                   ORDER BY      salary DESC
                 ) AS rnk
    from    employees
    )
where   rnk = 3

RNK LAST_NAME DEPARTMENT_ID SALARY
3 Ford 1 110000
3 Palazzo 2 68525

字符串

相关问题