SELECT tblOrders.OrderID, tblOrders.EmpNo, tblOrders.OrderDate, DateDiff("d",Nz(DMax(" [OrderDate] ","[tblOrders]"," [EmpNo] =" & [EmpID] And "[OrderDate]<= #" & [OrderDate] & "#"),[OrderDate]),[OrderDate]) AS DatesBetween
FROM tblEmploees INNER JOIN tblOrders ON tblEmploees.EmpID = tblOrders.EmpNo
ORDER BY tblOrders.OrderID;
I find Allen Browns examples really good for this see http://allenbrowne.com/subquery-01.html In the attached database I wrote the query Prior Visits just by substituting your problem into the "Get the value from another record example"
I also included a query, "Day Between Prior Visits" which does the math. Excuse that name. It doesn't really fit.
This query doesn't handle the case where there was no prior visit. You can deal with that with the iff function. If you have problems let me know.
Note: I used the first database you uploaded.
Once you get your DMax working, then you can put your DateDiff around it to calculate the difference in days. Did your DMax return the correct date for each record?
If the subquery has TOP 1 in it I don't understand how it could be returning more than one record. Could you upload the database. Maybe I can figure out what's wrong.
i think that because some emploees having more than one Order in the same date.
SELECT tblOrders.EmpName, tblOrders.OrderID, tblOrders.OrderDate, (SELECT TOP 1 Dupe.OrderDate
FROM tblOrders AS Dupe
WHERE Dupe.EmpName = tblOrders.EmpName
AND Dupe.OrderDate < tblOrders.OrderDate
ORDER BY Dupe.OrderDate DESC, Dupe.OrderID) AS PriorVist
FROM tblOrders;
How can I use this function, please
open recordset
lastdate = recordset!dateofvisit
rst.movenext
previousdate = recordset!dateofvisit
close recordset
Post #14:
We've been moving towards that. Does your DMax work yet?