在两个不同的表中为同一员工选择最大日期

时间:2014-02-27 06:04:56

标签: mysql sql date maxdate

我有两个包含员工信息的表格,我想选择这些表格中最新日期的记录。

Table1  
EmpNum      Name      StartDate      refrance  
1234        John      05Dec2009      999999    
1255        Carl      06May2003      454545  
1236        Smith     15Jan2011      889898

Table2  
EmpNum      Name      StartDate      refrance  
1234        John      08Feb2014      111111    
1255        Carl      25Jul2001      454545  
1236        Smith     15Jan2011      889898  

Expected output  
EmpNum      Name      StartDate      refrance  
1234        John      08Feb2014      111111    
1255        Carl      06May2003      454545  
1236        Smith     15Jan2011      889898

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT EmpNum,Name,Max(StartDate),refrance 
FROM (
      SELECT * FROM Table1
      Union All
      SELECT * FROM Table2
      ) AS T
Group By EmpNum,Name

答案 1 :(得分:1)

select 
  EmpNum, 
  Name,
  if(t1.startDate>t2.startDate,t1.startDate,t2.startDate) as maxDate,
  if(t1.startDate>t2.startDate,t1.refrance,t2.refrance) as refrance
from table1 t1
     join table2 t2 on t1.EmpNum=t2.EmpNum