Sql 使用GROUP BY后查找具有最大值的行

Sql 使用GROUP BY后查找具有最大值的行,sql,datetime,subquery,max,greatest-n-per-group,Sql,Datetime,Subquery,Max,Greatest N Per Group,我有一个4列的表格:dept\u no,emp\u no,from\u date,to\u date,其中对于每个dept\u no,emp\u no是经理 我想用到日期查找当前经理,我想显示部门号和emp号 样本数据: |emp_no |dept_no | from_date | to_date | | 11 | d001 | 1985-01-01 | 1991-10-01 | | 12 | d001 | 1991-10-01 | 9999-01-01

我有一个4列的表格:
dept\u no,emp\u no,from\u date,to\u date
,其中对于每个
dept\u no
emp\u no
是经理

我想用
到日期
查找当前经理,我想显示
部门号
emp号

样本数据:

|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(截止日期)
,然后在
WHERE
子句中使用它

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


我看到过许多类似的问题,但没有一个对我有帮助,因为我想显示一个不能在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)
对于此查询的性能,您需要
(部门号,截止日期)
上的索引

另一种常用方法是窗口函数:

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

根据您的数据库和版本,可能会有更整洁的替代方案。

请分享一些示例数据和预期结果。您可以使用行号。请参阅MySQL SQL Server。请只标记一个数据库。使用子查询进行筛选很有效,似乎是我想要做的最好的方法。非常感谢。