Im working with a database of heart transplant catheter procedures on patients. I'm trying to get the exam information for a number of patients from their exam closest to a given date.
When a patient comes in for a regular checkup, they usually have a cath procedure done that day, but occasionally, due to scheduling issues, it may be postponed a week or two or if a procedure was done recently before their checkup. So there is a window of + or - 14 days. However, supposing their procedure is positive for some problem, they may have it repeated again within that window. e.g. patient X has a procedure the day after his checkup that shows a problem, after treatment he has a follow-up procedure 5 days later. I'm only interested in the one procedure closest to the checkup date.
I have a table,PatientDates of PatientIDs and CheckDates. The procedure database, Cath, has a fields: CathKey (procedure primary key), PatientID, CathDate, Result1, Result2, etc.
I need to return the CathKey for the CathDate closest to CheckDate for each PatientID.
essentially:
Select PatientID, first(CathKey)
From PatientDates Inner Join Cath on PatientDates.PatientID = Cath.PatientID
Where CathDate between CheckDate+14 and CheckDate-14
GroupBy PatientID, CathKey
Having abs(CathDate-CheckDate) = min(abs(CathDate-CheckDate));
This doesn't work because it's grouped by Cathkey, but if I use first(CathKey), it doesn't correspond the the closest date.
When a patient comes in for a regular checkup, they usually have a cath procedure done that day, but occasionally, due to scheduling issues, it may be postponed a week or two or if a procedure was done recently before their checkup. So there is a window of + or - 14 days. However, supposing their procedure is positive for some problem, they may have it repeated again within that window. e.g. patient X has a procedure the day after his checkup that shows a problem, after treatment he has a follow-up procedure 5 days later. I'm only interested in the one procedure closest to the checkup date.
I have a table,PatientDates of PatientIDs and CheckDates. The procedure database, Cath, has a fields: CathKey (procedure primary key), PatientID, CathDate, Result1, Result2, etc.
I need to return the CathKey for the CathDate closest to CheckDate for each PatientID.
essentially:
Select PatientID, first(CathKey)
From PatientDates Inner Join Cath on PatientDates.PatientID = Cath.PatientID
Where CathDate between CheckDate+14 and CheckDate-14
GroupBy PatientID, CathKey
Having abs(CathDate-CheckDate) = min(abs(CathDate-CheckDate));
This doesn't work because it's grouped by Cathkey, but if I use first(CathKey), it doesn't correspond the the closest date.