2016-11-07 111 views
1

我有兩個只有3個公共字段的表。 我寫了下面的查詢回暖與最新的日期丟失的數據如表1在Oracle中選擇最近日期的缺失記錄

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; 

的電流Ouptput我得到的是

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

希望你能忽略了NOT EXISTS子句中的DateField。

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 
) 
+0

Maheshwaran如果我刪除日期字段它將返回表1中不是我不需要的所有缺少的數據。我需要檢查每個類別員工的最新記錄是否來自表1,如果是,我需要填充它或忽略 –

+0

更新後的SQL應該有幫助。 –

+0

之前嘗試過,但它做的工作 –