I have a table of "patient visits" where each row records a single patient-visit event. In simplified form, the table is like this:
CREATE TABLE #MyVisits (
PatientID char(10) NOT NULL, --Alphanumeric Patient ID
VisitID char(10) NOT NULL, --Alphanumeric Visit ID
Clinic varchar(10) NOT NULL, --Name of clinic visited
DateVisit date NOT NULL --Date of visit
EarliestVisitComment varchar(100) NULL -- Free text field
)
Patients - who always have the same Alphanumeric ID - may have only ever visited once, or very infrequently, or regularly.
What I need to do is, for each row, see if the given patient (using the PatientID field) had any prior visit within the previous 90 days (i.e. DateVisit minus 90 days), and record the Clinic + ' ' + VisitID for that visit (as a single string) in the EarliestVisitComment field.
If the patient has had multiple visits in the 90-day look-back window, I only want to identify the first / earliest visit the patient had in that window.
(If there is only one visit, then EarliestVisitComment can be null or blank.)
I have got as far as using ROW_NUMBER to partition and rank the data, but it feels like I am a long way off correctly grabbing the value I need, espcially as I have no interest in sequential visits more than 90 days apart. I have tried working with LAG() and NTILE() but feel stuck. I am sure I can figure our a "row-by-agonising-row" approach but hopefully there is a better way. Is there a kind SQL guru out there who can help?