With a CTEWith e (Inspection_Date, Formatted_Licence_Number, Inspections_Facts_Key, id)AS ( SELECT Inspection_Date, Formatted_Licence_Number, t2.Inspections_Facts_Key, RowNumber() OVER (partition by Inspection_Date, Formatted_Licence_Number ORDER BY Inspection_Date DESC) as id FROM Infodbo.Licensing_Facts t1 INNER JOIN Infodbo.Inspections_Facts t2 ON t1.Licensing_Facts_Key = t2.Licensing_Facts_Key WHERE t1.Type_Code = 'fp' AND t1.Class_Code = 'health' AND t2.Result_Code IS NOT NULL)SELECT Inspection_Date, Formatted_Licence_Number, Inspections_Facts_KeyFROM eWHERE id = 1;
With a correlated subquerySELECT Inspection_Date, Formatted_Licence_Number, t2.Inspections_Facts_Key,FROM Infodbo.Licensing_Facts t1INNER JOIN Infodbo.Inspections_Facts t2ON t1.Licensing_Facts_Key = t2.Licensing_Facts_KeyINNER JOIN ( SELECT Formatted_Licence_Number, MAX(Inspection_Date) dt FROM Infodbo.Licensing_Facts t1 INNER JOIN Infodbo.Inspections_Facts t2 ON t1.Licensing_Facts_Key = t2.Licensing_Facts_Key GROUP BY Formatted_Licence_Number) xOn x.Formatted_Licence_Number = t1.Formatted_Licence_NumberAnd x.dt = t2.Inspection_DateWHERE t1.Type_Code = 'fp' AND t1.Class_Code = 'health' AND t2.Result_Code IS NOT NULL;