Ok, so this feels like a complicated query due to a poor design of the database, but alas -- it is there and in need of solving. The table has 5 fields: id(PK), itemNumber(FK), completedDate, completedBy(FK), nextDue.
In the application, when someone records a task as being done, it fills in the completedDate, calculates the next due date and puts that in nextDue.
What I need, is a query that will basically look at a record's nextDue date, then look ahead to the next record that has the same itemNumber, and compare with that completedDate; then return the row if the completedDate exceeds the completedBy date. Does that make sense? Can this be done? It sounds like it would have to be done procedurally vs. pure sql. TIA
UDPATE: I guess I should be more specific. I need to use this query in a report, so if it needs to be done in VBA, I'm not sure how to get the results into that.
I find the best way to think about these weird queries is to break 'em down into smaller manageable queries in my mind. So, I think about this as first associating and then comparing two records: The 'current' and the 'next' records. The first thing we want to do is associate each record (which will become the 'current') with it's corresponding 'next' record.
So, first, a query that gets all records IDs and their corresponding "next record". This uses a less than "<" in the JOIN statement to get all of the records that are after the current record.
SELECT
T.id as currentId,
MIN(A.id) as nextId
FROM
rec_completionDate as T
JOIN
rec_completionDate as A ON T.itemNumber = A.itemNumber and T.id < A.id
GROUP BY
T.id
Follow it up with a query that, using the above as a subquery, returns all of the appropriate fields for each record (current and next):
SELECT
current.*,
next.*
FROM
( ... [subquery goes here] ...) sq
JOIN
rec_completionDate as current ON sq.currentId = current.id
JOIN
rec_completionDate as next ON sq.nextId = next.id
Lastly, we'll want to limit the results of that last query with the following WHERE clause:
WHERE
next.completedDate > current.nextDue
So, putting it all together:
SELECT
current.*,
next.*
FROM
(
SELECT
T.id as currentId,
MIN(A.id) as nextId
FROM
rec_completionDate as T
JOIN
rec_completionDate as A ON T.itemNumber = A.itemNumber and T.id < A.id
GROUP BY
T.id
) sq
JOIN
rec_completionDate as current ON sq.currentId = current.id
JOIN
rec_completionDate as next ON sq.nextId = next.id
WHERE
next.completedDate > current.nextDue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.