相关子查询外部查询的多个结果

nzk0hqpo  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(314)

我想知道是否有可能让内部查询返回多个结果,然后由外部查询查询?
下面是一个可复制的示例:
在这个例子中,我想知道每个部门薪水最高的员工的姓名和薪水。

CREATE TABLE Worker (
    WORKER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    FIRST_NAME CHAR(25),
    LAST_NAME CHAR(25),
    SALARY INT(15),
    JOINING_DATE DATETIME,
    DEPARTMENT CHAR(25)
);

INSERT INTO Worker 
    (WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT) VALUES
        (001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR'),
        (002, 'Niharika', 'Verma', 80000, '14-06-11 09.00.00', 'Admin'),
        (003, 'Vishal', 'Singhal', 300000, '14-02-20 09.00.00', 'HR'),
        (004, 'Amitabh', 'Singh', 500000, '14-02-20 09.00.00', 'Admin'),
        (005, 'Vivek', 'Bhati', 500000, '14-06-11 09.00.00', 'Admin'),
        (006, 'Vipul', 'Diwan', 200000, '14-06-11 09.00.00', 'Account'),
        (007, 'Satish', 'Kumar', 75000, '14-01-20 09.00.00', 'Account'),
        (008, 'Geetika', 'Chauhan', 90000, '14-04-11 09.00.00', 'Admin');

找到每个部门的最高工资很容易:

SELECT MAX(SALARY), DEPARTMENT
FROM Worker
GROUP BY DEPARTMENT;

但是,我又该如何在结果中加上赚取这些薪水的雇员的名字呢?
非常感谢!

6fe3ivhb

6fe3ivhb1#

您可以将查询与运算符一起使用 IN :

SELECT * FROM Worker
WHERE (DEPARTMENT, SALARY) IN (
  SELECT DEPARTMENT, MAX(SALARY) 
  FROM Worker
  GROUP BY DEPARTMENT 
);

或者如果您使用mysql 8.0+和 RANK() 窗口功能:

SELECT w.* 
FROM (
  SELECT *, RANK() OVER (PARTITION BY DEPARTMENT ORDER BY SALARY DESC) rnk
  FROM Worker
) w
WHERE w.rnk = 1

请看演示。
结果:

> WORKER_ID | FIRST_NAME | LAST_NAME | SALARY | JOINING_DATE        | DEPARTMENT
> --------: | :--------- | :-------- | -----: | :------------------ | :---------
>         3 | Vishal     | Singhal   | 300000 | 2014-02-20 09:00:00 | HR        
>         4 | Amitabh    | Singh     | 500000 | 2014-02-20 09:00:00 | Admin     
>         5 | Vivek      | Bhati     | 500000 | 2014-06-11 09:00:00 | Admin     
>         6 | Vipul      | Diwan     | 200000 | 2014-06-11 09:00:00 | Account

相关问题