I have a data set like this:
PatientId AssessDate Reading
-------- --------------- ----------------
1000 2021-01-28 31
1000 2020-12-29 28
1000 2020-11-31 32
1000 NULL NULL
1001 2021-01-27 21
1001 2020-12-25 22
1001 2020-11-26 24
1001 NULL NULL
1001 2020-09-18 26
........
If I do a query like:
select PatientID, MAX(AssessDate)
From Table1
Group by PatientID
PatientId AssessDate
-------- ---------------
1000 2021-01-28
1001 2021-01-27
I get all the Max AssessDates for each patient.
However if I try adding the "readings" column as part of above I get all readings for each patient, not just the one associated with the max date. I kind of suspected this was going to happen, and thought there might be a way with partition/CTE table solution.
On top of this, I also want to get the 2nd last "reading" before the max assess date, bearing in mind some of the readings can be null, so it should pull the next most recent one (By date order).
I tried some variations of different ideas with "having", partion with rowID and can't seem to get it working.
Any idea how I can get the 2nd last "Max" date reading as well as show the "reading" without it affecting the data set returned? My end result would be this:
PatientId AssessDate Reading
-------- --------------- ----------------
1000 2021-01-28 31
1000 2020-12-29 28
1001 2021-01-27 21
1001 2020-12-25 22
Thanks
G