I have a table called PayApplications
PayApplications
---------------
ID
JobID (fk long)
PeriodTo (date, always last day of a month for which this app applies)
ApplicationDate (date record was created)
What I would like to be able to do is select all of the PayApplications for a specific job (JobID) AND along with each PayApplication return the ID field of the PayApplication with the closest previous PeriodTo date (from the same job).
Code:
SELECT
ID,
PeriodTo,
ApplicationDate,
PreviousPayApplicationID <-----------THIS IS THE PICKLE, HOW DO I GET THIS???
FROM PayApplications AS pa
WHERE JobID=[some job id]
Now I know I can do a subquery like so:
Code:
(SELECT TOP 1 PayApplicationID
FROM PayApplications As prev_pa
WHERE prev_pa.JobID=pa.JobID
AND prev_pa.PeriodTo<pa.PeriodTo
ORDER BY prev_pa.PeriodTo DESC)
HOWEVER it's buggy, this subquery causes funny issues down road in stacked queries that force me to use outer joins when I don't want them otherwise it'll crash access.
In testing if I add a PreviousPayApplicationID field directly to the table, and manually enter the appropriate foreign key then all my stacked queries and joins work like they are supposed to, so I know they aren't the problem. But this is kind of a calculated value that I'd rather calculate at run time than store in the PayApplication table.
I've already devised one solution that is a vba function that given a JobID it will loop through the Job's PayApplications and set each PrevPayApplicationID field correctly, I can call this function from a WHERE clause in my query, but this feels like a dirty hack...
So is there another way to query what I'm after besides the SELECT TOP 1 subquery?