Ask the Expert

Latest contract period for each employee

I have an MS Access table with employee information and contract periods. Each contract period has a unique ID, but may of course have the same employee number with different contract start date and contract end date. How can I use this table to find the last contract period for each employee? You can assume that one contract doesn't start until the previous one ends.

Assuming your table looks like this --

cID  cStart      cEnd        cEmpl
122  2002-01-01  2002-03-31  john
123  2002-01-01  2002-02-28  fred
124  2002-01-01  2002-09-30  bill
125  2002-04-01  2002-04-30  fred
126  2002-05-01  2002-05-31  fred
127  2002-04-01  2002-06-30  john
128  2002-11-01  2002-12-31  bill

The query must find the latest contract for each employee, and since one contract doesn't start until the previous one ends, we can use MAX(cStart). Using the start date rather than end date is preferable, since this allows ongoing contracts to have a null end date, although this might not apply in your situation.

However, that's not enough to give the entire contract period. You need both the start date and the end date. But how can you get the end date when selecting MAX(cStart)? The answer is to use a correlated

    Requires Free Membership to View

subquery:

select cID, cStart, cEnd, cEmpl
  from yourtable XX
 where cStart = 
       ( select max(cStart)
           from yourtable
          where cEmpl = XX.cEmpl )

Here, the correlation is on the employee column. The outer query's WHERE clause accepts only those rows where cStart is the highest for that employee.

There's another way to do this, using a derived table in a join; see Rows having maximum group value in MySQL. Note that in MySQl, you have to do it in two steps using a temp table.


This was first published in November 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: