I have a table named tblHumanResources
in which I want to get the collection of rows which consists of the latest 2 rows per distinct empID
. (Latest in terms of effectiveDate
).
Scenario: I want the collection of entries to be ordered by empID, and then get 2 rows per empID which has the latest effectiveDate (top 2 of effectiveDate if ordered in a descending manner).
Note: I am using SQL Server 2008 and my table has thousands of rows.
tblHumanResources
Table
| empID | effectiveDate | Company | Description
| 0-123 | 1999-04-18 | DFD Comp | Analyst
| 0-234 | 2007-04-22 | ABC Comp | Manager
| 0-222 | 2012-02-19 | CDC Comp | Janitor
| 0-213 | 2009-05-03 | CBB Comp | Teller
| 0-223 | 2012-01-23 | CBB Comp | Teller
| 0-223 | 1999-05-27 | CBB Comp | Teller
| 0-123 | 2014-01-25 | DFD Comp | Analyst
| 0-234 | 1999-01-23 | ABC Comp | Manager
| 0-222 | 2014-12-13 | CDC Comp | Janitor
| 0-213 | 2014-02-12 | CBB Comp | Teller
| 0-223 | 2005-03-26 | CBB Comp | Teller
| 0-123 | 2005-02-05 | DFD Comp | Analyst
| 0-234 | 2014-05-18 | ABC Comp | Manager
| 0-222 | 2001-06-23 | CDC Comp | Janitor
| 0-213 | 2003-05-12 | CBB Comp | Teller
//and so on...
I want to display something like this:
| empID | effectiveDate | Company | Description
| 0-123 | 2014-01-25 | DFD Comp | Analyst
| 0-123 | 2005-02-05 | DFD Comp | Analyst
| 0-213 | 2014-02-12 | CBB Comp | Teller
| 0-213 | 2009-05-03 | CBB Comp | Teller
| 0-222 | 2014-12-13 | CDC Comp | Janitor
| 0-222 | 2012-02-19 | CDC Comp | Janitor
| 0-223 | 2012-01-23 | CBB Comp | Teller
| 0-223 | 2005-03-26 | CBB Comp | Teller
| 0-234 | 2014-05-18 | ABC Comp | Manager
| 0-234 | 2007-04-22 | ABC Comp | Manager
//and so on...
Any help would be much appreciated.
PS: I wouldn't be able to try your codes right now for my dev laptop isn't with me. I'd be trying your answers after a few hours to be able to properly choose the answer that solves the problem.
Thank you.