I have a query who return something like it :
Name Gender Job date of hire
John M mechanic 2012-05-08
John M electrician 2010-01-01
Vicky F scientific 2012-11-11
Bob M NULL NULL
I need to have the name, gender and jobname of first job of each person. But i don't know how.
My query look like this :
select name,gender,jobname,hiredate
from person p
left join job j on p.personid = j.personid
I'm on Microsoft SQL Server 2000
I need this as result :
Name Gender Job
John M electrician
Vicky F scientific
Bob M NULL
Best Answer
I infer that your data looks like this:
Person Table
Job Table
The first task is to find the first job (by hire date) for each person. One neat way to do that is by using a correlated subquery:
Notice the correlation
WHERE j2.PersonID = j.PersonID
between the inner and outer queries there. The output of that query is:The execution plan (given a clustered
PRIMARY KEY
onPersonID, HireDate
) is:The interesting thing about that plan is the Job table is only scanned once, despite there being two references to it in the original query. The plan uses an optimization that I call Segment Top. Essentially the execution engine takes advantage of the index order to detect the start of a new group (segment) and take just the first row from each group (top).
Now that we have that result, all we need do is join it back to the Person table:
The execution plan is:
The
OPTION (MERGE JOIN)
is not required; I just added it to show the plan you are likely to get when the tables contain a larger number of rows than in this small example.Table definitions and sample data: