Hi
I need help to find out latest Effective_Dates form below list (sample from a large table tblPayRateHist). So far I am able to get top 3 values from the list but I end up with duplicate Effective_Date for 01/01/2015 because There are two entries for this date with Different Change_Date.
I tried this which gives me duplicate Effective_date:
"SELECT tblPayRateHist.EmployeeID, tblPayRateHist.PayRateID, tblPayRateHist.CHANGE_DATE, tblPayRateHist.EFFECTIVE_DATE
FROM tblPayRateHist
GROUP BY tblPayRateHist.EmployeeID, tblPayRateHist.PayRateID, tblPayRateHist.CHANGE_DATE, tblPayRateHist.EFFECTIVE_DATE
HAVING (((tblPayRateHist.EFFECTIVE_DATE) In (SELECT TOP 3 EFFECTIVE_DATE
FROM [tblPayRateHist] AS T1
WHERE T1.EmployeeID=[tblPayRateHist].[EmployeeID])))
ORDER BY tblPayRateHist.EmployeeID, tblPayRateHist.EFFECTIVE_DATE;"
PayRateHistID........ EmployeeID........... PayRateID........... CHANGE_DATE................ EFFECTIVE_DATE 51798 21 110 31/12/2007 14/12/2007 51795 21 93 27/11/2008 1/01/2008 51799 21 111 27/05/2008 16/05/2008 51800 21 111 3/10/2008 19/09/2008 51796 21 93 13/01/2009 1/01/2009 51797 21 94 25/08/2009 14/08/2009 51785 21 68 8/09/2009 28/08/2009 51786 21 68 21/05/2010 1/01/2010 51787 21 68 15/01/2011 1/01/2011 51788 21 70 11/01/2012 1/01/2011 51790 21 71 5/09/2012 1/01/2011 51789 21 70 24/02/2011 14/02/2011 51791 21 71 2/12/2013 1/01/2012 51792 21 71 2/01/2014 1/01/2014 51793 21 71 25/03/2014 20/03/2014 51794 21 71 15/01/2015 1/01/2015 51784 21 24 15/04/2015 1/01/2015
What I am trying to achieve is to Get the Top n Effective_Dates and the corresponding PayRateID for Each Employee until a cut-off date has reached.
For Example, If the cut-off Date is 01/01/2014 then I should have below items. Same Effective_Date with later Change_Date takes priority over one with earlier Change_Date And I should not have Same Effective_Date more then once.
PayRateHistID........... EmployeeID......... PayRateID.......... CHANGE_DATE................. EFFECTIVE_DATE 51792 21 71 2/01/2014 1/01/2014 51793 21 71 25/03/2014 20/03/2014 51784 21 24 15/04/2015 1/01/2015
Your help is much appreciated. Please note I am new to database and trying to learn SQL.