在Oracle中选择包含最新日期的缺失记录

时间:2016-11-07 06:11:23

标签: sql oracle

我有2个表,只有3个公共字段。 我写了下面的查询来获取表1中最新日期的缺失数据。

Employee Category Date_Field   First_Name Last_Name Status   Result
100      Type1    30/08/2010   A          B          Present  Good
200      Type1    1/09/2010    C          D          Hello    Alt
100      Type3    30/09/2010   A          B 
100      Type1    30/09/2012   A          B 


Employee Category Date_Field   
100      Type1     03/11/2016 
100      Type3     30/09/2010 
100      Type4     11/10/2010
200      Type3     12/12/1989

我的查询

with x1 as (SELECT Employee,Category,Date_Field,First_Name,Last_Name,Status,Result,' ' as Somefield from table 1
where not exists 

(select 1 from table2
where table1.employee=table2.employee and table1.category = table2.Category
and table1.Date_Field = table2.Date_Field)),

x2 as (select Employee,Category,Max(Date_Field) as DateField from x1 group by Employee)

select x1.Employee,x1.Category,x1.Date_Field,x1.First_Name,x1.Last_Name,x1.Status,x1.Result,x1.Somefield from x1,x2
where x1.Employee = x2.Employee and x1.Date_Field=x2.DateField and x1.Category=x2.Category
order by x1.Employee;

我得到的当前输出是

Employee Category Date_Field  First_Name Last_Name Status Result
100     Type1     30/09/2012  A           B 
200     Type1     1/09/2010   C           D        Hello Alt

我是否可以修改此查询,以便在表2中找到具有最新日期和类别的同一员工的记录时,我的输出不应该有该记录。

所以预期的输出是

Employee Category Date_Field First_Name Last_Name Status Result
200      Type1    1/09/2010  C          D         Hello  Alt

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

希望您可以忽略NOT EXISTS子句的日期字段。

SELECT * FROM TABLE1 T1
WHERE NOT EXISTS
(
  SELECT 'x' FROM TABLE2 T2
  WHERE T1.EMPLOYEE = T2.EMPLOYEE
   AND T1.CATEGORY = T2.CATEGORY
   AND T2.DATEFIELD >= T1.DATEFIELD
)