使用 GROUP BY 后查找具有 MAX 值的行

Finding rows with MAX value after using GROUP BY

我有一个包含 4 列的 table:dept_no, emp_no, from_date, to_date,其中每个 dept_noemp_no 是经理。

我想使用 to_date 查找当前经理,我想显示 dept_noemp_no

示例数据:

|emp_no  |dept_no  | from_date  |   to_date  |
| 11     | d001    | 1985-01-01 | 1991-10-01 |
| 12     | d001    | 1991-10-01 | 9999-01-01 |
| 21     | d002    | 1985-01-01 | 1989-12-17 |
| 22     | d002    | 1989-12-17 | 9999-01-01 |
| 31     | d003    | 1985-01-01 | 1992-03-21 |
| 32     | d003    | 1992-03-21 | 9999-01-01 |

示例输出:

|emp_no   |dept_no  |
|12       |d001     |
|22       |d002     |
|32       |d003     |

我想通了:

SELECT dept_no
     , emp_no 
  FROM 
     ( SELECT dept_no
            , MAX(to_date) as cur 
         FROM dept_manager 
        GROUP 
           BY dept_no) as new 
  JOIN dept_manager using(dept_no) 
 where cur = to_date;

我正在为每个部门找到 MAX(to_date),然后在 WHERE 子句中使用它。

这可行,但我觉得应该有更好的方法来做到这一点。

我见过很多类似的问题,但是 none 帮助了我,因为我想显示一个不能在 group by 中使用的列。

一种可移植且通常有效的方法是使用子查询进行过滤:

select dept_no, emp_no
from dept_manager d
where to_date = (select max(d1.to_date) from dept_manager d1 where d1.dept_no = d.dept_no)

为了提高此查询的性能,您需要在 (dept_no, to_date) 上建立索引。

另一个常见的方法是window函数:

select *
from (
    select d.*, row_number() over(partition by dept_no order by to_date desc) rn
    from dept_manager d
) d
where rn = 1

根据您的数据库和版本,可能有更简洁的选择。