如果最大薪水与多个员工相同,如何只从每个部门获得一个员工姓名

时间:2016-04-02 08:24:55

标签: oracle plsql correlated-subquery

我正在使用以下查询:

SELECT rownum, job_id, employee_id, first_name, last_name, phone_number, salary
FROM employees OUTER
WHERE salary =
(
SELECT MAX(salary)
FROM employees
WHERE job_id = OUTER.job_id
GROUP BY job_id
)
AND ROWNUM < 6;

低于结果:

1   AD_PRES 100 Steven  King    515.123.4567    24000
2   AD_VP   101 Neena   Kochhar 515.123.4568    17000
3   AD_VP   102 Lex De Haan 515.123.4569    17000
4   IT_PROG 103 Alexander   Hunold  590.423.4567    9000
5   FI_MGR  108 Nancy   Greenberg   515.124.4569    12008

table

但问题是我只希望每个JOB_ID都有一个名字。这应该由FIRST_NAME中的字母顺序决定。

2 个答案:

答案 0 :(得分:0)

一种选择是使用包含job_id的子查询作为要保留的名字。我将原始查询包装在公用表表达式中,以使其更具可读性。

WITH t AS
(
    SELECT rownum, job_id, employee_id, first_name, last_name,
        phone_number, salary
    FROM employees OUTER
    WHERE salary =
    (
        SELECT MAX(salary)
        FROM employees
        WHERE job_id = OUTER.job_id
        GROUP BY job_id
    )
    AND ROWNUM < 6;
)

SELECT t1.rownum, t1.job_id, t1.employee_id, t1.first_name, t1.last_name,
    t1.phone_number, t1.salary
FROM t t1
INNER JOIN
(
    SELECT job_id, MAX(first_name) AS max_name
    FROM t
    GROUP BY job_id
) t2
    ON t1.job_id = t2.job_id AND t1.first_name = t2.max_name

答案 1 :(得分:0)

使用analytic functions

select * from (
    SELECT job_id, employee_id, first_name, last_name, phone_number, salary,
    RANK() over (
        job_id 
       order by 
           salary desc, 
           first_name, 
           employee_id -- adding employe_id breaks ties in the ordering 
       ) as rnk 
    FROM employees 
) where rnk = 1;

这可能也会比subselect更好。

所有这些都是在没有数据库的情况下编写的,因此它可能/将包含拼写错误