Oracle SQL 11g获得每个类别的最新信息

时间:2018-07-12 15:51:56

标签: sql oracle oracle11g

使用下表。我需要获取每个date_joined中最新的DEPT

 __________________________________
| DEPT     | DATE_JOINED | MANAGER |
|----------------------------------|
|  Produce | 30-JUL-15   | George  |
|  Grocery | 05-FEB-18   | Michael |
|  Produce | 30-JAN-18   | Joe     |
|  Grocery | 01-OCT-10   | Susan   |
|  Grocery | 25-SEP-17   | Sam     |    
|  Produce | 03-JUN-18   | Lizzy   |
|__________________________________|

想要的结果是每个部门加入的最新日期:

 __________________________________
| DEPT     | DATE_JOINED | MANAGER |
|----------------------------------|
|  Grocery | 05-FEB-18   | Michael |
|  Produce | 03-JUN-18   | Lizzy   |
|__________________________________|

1 个答案:

答案 0 :(得分:2)

一种简单的方法使用相关子查询:

select t.*
from t
where t.date_joined = (select max(t2.date_joined) from t t2 where t2.dept = t.dept);

但是,在这种情况下,我的运气(在性能方面)不错:

select dept, max(date_joined) as date_joined,
       max(manager) keep (dense_rank first order by date_joined desc) as manager
from t
group by dept;