MySql 5.5.
I have a table that represents a work assignment:
empId jobNo workDate hours
4 441 10/1/2012 10
4 441 9/1/2012 22
4 441 8/1/2012 6
And one that represents salary:
empId effDate rate
4 10/1/2012 6.50
4 9/1/2012 5.85
4 6/1/2012 4.00
The salary applies to all work performed on or after the effective date. So the rate in jun, jul, and aug is 4.00; sep is 5.85, and oct is 6.50.
If I naively query for October’s work:
SELECT Work.empId, Work.jobNo, Work.workDate, Work.hours, Salary.effDate, Salary.rate
FROM Work
JOIN Salary ON Work.empId = Salary.empId
WHERE Work.workDate <= '2012-10-01'
AND Salary.effDate <= Work.workDate
ORDER BY Work.jobNo ASC, Work.workDate DESC;
I do not get what I want. I get something like
4 441 10/1/2012 10 10/1/2012 6.50
4 441 10/1/2012 10 9/1/2012 5.85
4 441 10/1/2012 10 6/1/2012 4.00
4 441 9/1/2012 22 9/1/2012 5.85
4 441 9/1/2012 22 6/1/2012 4.00
4 441 8/1/2012 6 6/1/2012 4.00
When I want
4 441 10/1/2012 10 10/1/2012 6.50
4 441 9/1/2012 22 9/1/2012 5.85
4 441 8/1/2012 6 6/1/2012 4.00
I can’t quite wrap my head around how to create the query I want.
The real situation has multiple employees, multiple jobs, obviously.
Thanks for your help.
Here is your actual issue: you want to be able to detect, for each record in Work, what is the corresponding effective rate, according to the work date x salary effective date. When you simply do
Salary.effDate <= WORK.workDateyou get ALL rates before the work date. But you only want the most recent one.This is a slightly complicated variant of the greatest-n-per-group problem. There are many ways of doing this, here is one:
First of all, the inner query detects the most recent salary effective date for each work record. Then, we join that with the Salary again to the rate.
See the working SQLFiddle.