从连接表中检索MAX(日期)值

时间:2016-03-23 13:24:58

标签: sql oracle join greatest-n-per-group

我需要一个非常基本的SQL连接概念的帮助,我似乎无法做对。

我有一张员工表和一张位置表。员工表就像这样:

EmpID   Name
1       Jane Jones
2       Bob Smith
3       Jim Adams

位置表是这样的:

PosID   EmpID        Position   DateFilled
1       1            Sales      1/2/2012
2       2            HR         4/5/2013
3       2            Mgmnt      6/1/2014
4       2            Sr. Mgmnt  7/5/2015
5       3            IT Support 4/6/2014
6       3            IT Devel.  5/11/2015

如何获得以下输出:

EmpID   Name        Position    DateFilled
1       Jane Jones  Sales       1/2/2012
2       Bob Smith   Sr. Mgmnt   7/5/2015
3       Jim Adams   IT Devel.   5/11/2015

因此,换句话说,我如何加入以获取位置表中只有最大DateFilled列的记录才能与employee表中的相应记录一起加入? 非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER

SELECT e.EmpID, e.Name, p.Position, p.DateFilled
FROM employee e
LEFT JOIN (
   SELECT EmpID, Position, DateFilled,
          ROW_NUMBER() OVER (PARTITION BY EmpID 
                             ORDER BY DateFilled DESC) AS rn        
   FROM position
) p ON e.EmpID = p.EmpID AND p.rn = 1

答案 1 :(得分:1)

你可以使用MAX() KEEP ( DENSE_RANK [FIRST|LAST] ... )这样做:

SELECT e.EmpId,
       e.Name,
       p.position,
       p.datefilled
FROM   employee e
       INNER JOIN (
         SELECT EmpID,
                MAX( Position ) KEEP ( DENSE_RANK LAST ORDER BY DateFilled ) AS Position,
                MAX( DateFilled ) AS DateFilled
         FROM   position
         GROUP BY EmpID
       ) p
       ON ( e.EmpId = p.EmpID );

答案 2 :(得分:0)

试试这个

 select temp.EmpID,(select position from Position where PosID =temp.PosID) position,DateFilled,Name from 
    (select EmpID,max(PosID) PosID,max(DateFilled) DateFilled 
     from position group by EmpID ) temp
    inner join employee  emp on emp.EmpID =temp.EmpID