I am having a great deal of trouble with subqueries in Access.
I am trying to write a Payroll application, I have the following tables
PayRecords
+----+------------+--------+----------+
| Id | Date | Pay | Employee |
+----+------------+--------+----------+
| 0 | 19/04/2001 | 123.45 | 1 |
| 1 | 19/05/2001 | 123.45 | 1 |
| 2 | 19/06/2001 | 123.45 | 1 |
| 3 | 19/07/2001 | 123.45 | 1 |
| 4 | 19/08/2001 | 123.45 | 1 |
| 5 | 19/04/2001 | 97.68 | 2 |
| 6 | 19/05/2001 | 97.68 | 2 |
| 7 | 19/06/2001 | 97.68 | 2 |
| 8 | 19/07/2001 | 97.68 | 2 |
| 9 | 19/08/2001 | 97.68 | 2 |
+----+------------+--------+----------+
Employees
+----+------------+------------+
| Id | Surname | First name |
+----+------------+------------+
| 1 | Bloggs | Joe |
| 2 | Smith | Bill |
+----+------------+------------+
TaxCodes
+----+------------+------------+-------+
| Id | Date | Employee | Code |
+----+------------+------------+-------+
| 1 | 06/04/2001 | 1 | 99L |
| 2 | 06/06/2001 | 1 | 105L |
| 3 | 06/04/2001 | 2 | 150L |
| 4 | 06/07/2001 | 2 | 167L |
+----+------------+------------+-------+
The tax code table shows on what date a particular tax code applies for
an employee.
Once a tax code applies then earlier tax codes for that employee do not
apply.
So in the example above
Joe Bloggs has tax code 99L from 06/04/2001 until 06/06/2001 when he
then has tax code 105L
Similarly Bill Smith has tax code 150L from 06/04/2001 until 06/07/2001
when tax code 167L applies.
When working out the tax owed by an employee on each pay day I need to
determine which tax code is applicable.
This is where my problems lie.
What I think I want to query for is the tax code with the highest date
that is less than or equal to the PayRecords.Date field and that the
tax code and pay record employee fields are equal :-
SELECT PayRecords.Employee, PayRecords.Date,
PayRecords.PayTaxCodes.Code
FROM PayRecords, TaxCodes
WHERE (Max(TaxCodes.Date) <= PayRecords.Date) AND (PayRecords.Employee
= TaxCodes.Employee);
This gives me an error because you cannot have an aggregate function in
a WHERE clause.
After some research on the web I tried the following
SELECT PayRecords.Employee, PayRecords.Date, PayRecords.Pay,
TaxCodes.Code, TaxCodes.Date
FROM PayRecords, TaxCodes
WHERE PayRecords.Date >= (select Max(TaxCodes.Date) As TaxCodesDate
FROM TaxCodes WHERE (PayRecords.Employee = TaxCodes.Employee))
ORDER BY PayRecords.Employee, PayRecords.Date;
This query runs but it gives multple instances of the same payrecord
with different tax codes, some of which have dates later than the
payrecord's date. It seems to be ignoring the >= test
Does anybody know what I am doing wrong ?
I would be most grateful for any help people can offer.
regards
Darran