John,
I don't understand. You said "all the weight records retrieved in the
query have the same PatientID". So does that mean that all the data in
tblPatientWeights is for the same patient? And if so, why the "ORDER BY
PatientID" clause in the query?
So, assuming I understand what you want:
You can do this sort of thing with a SubQuery. Without testing, I think
something like this will work...
SELECT tblPatientWeights.PatientID, tblPatientWeights.ObsDate,
tblPatientWeights.Weight, blPatientWeights.Temp,
tblPatientWeights.HeartRate, tblPatientWeights.Bp, tblPatientWeights.RR,
(SELECT TOP 1 [Weight] FROM tblPatientWeights WHERE
[PatientID]=tblPatientWeights.[PatientID] And
[ObsDate]<tblPatientWeights.[ObsDate] ORDER BY [ObsDate] DESC) AS PrevWeight
FROM tblPatientWeights
If you have a lot of records in the query, though, this is likely to be
slow. In which case a User-Defined Function would be better. In a
standard module, it will be something like this...
Public Function FindPrev(MyPatient As Long, ThisObs As Long) As Long
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT Weight FROM
tblPatientWeights WHERE PatientID = " & MyPatient & " And ObsDate < " &
ThisObs & " ORDER BY ObsDate DESC")
FindPrev = rst!Weight
rst.Close
Set rst = Nothing
End Function
Then in your query you can do like this...
SELECT tblPatientWeights.PatientID, tblPatientWeights.ObsDate,
tblPatientWeights.Weight, blPatientWeights.Temp,
tblPatientWeights.HeartRate, tblPatientWeights.Bp, tblPatientWeights.RR,
FindPrev([PatientID],CLng([ObsDate])) AS PrevWeight
FROM tblPatientWeights
--
Steve Schapel, Microsoft Access MVP
Thanks again Steve,
Here is the code. The section from DlookUp is the code that is supposed to
look back at the last record. If i replace the PatientID field with the
ObsDate field should that work. Instead of ObsDate (-1) the code might have
to reflect an earlier date. Also, the DLookUp section would have to refer to
the query as there will be also many Patients with the same entry date in the
tblPatientWeights. That is why i thought of using a counter field in the
query so i could look back one record in the query itself. All queries and
tables must have a property somewhere to keep track of the record numbers as
shown at the bottom, is it possible to access that?
SELECT tblPatientWeights.PatientID, tblPatientWeights.ObsDate,
tblPatientWeights.Weight, tblPatientWeights.Temp,
tblPatientWeights.HeartRate, tblPatientWeights.Bp, tblPatientWeights.RR,
DLookUp("[Weight]","tblPatientWeights","[PatientID] = " & [PatientID]-1) AS
PrevWeight
FROM tblPatientWeights
ORDER BY tblPatientWeights.PatientID;