I have a table of patients (one) and a table of vital statistics (many). I need to get a list of the patients whose values of the last 2 readings in the year are over a certain value. Both of the last 2 need to be over a cretain threshold for the patient to be counted.
I can group on Patient_ID and count the number of values that are over the threshold, but that does not really account for only the last 2 values. It could be the 1st and the 3rd or the 7th and 15th.
The query below will show me those patients whose last value was over 160, but not the last 2. It gets me half way there.
What I've been doing to running multiple queries - one for each patient - that gets the TOP 2 Values ORDER BY EncounterDate DESC and put those in to a table. I then have the top 2 for each patient and I then group and count of patient ID where count > 1 and it works.
The problem is, this takes for ever. It is only 600 patients, but running a TOP 2 query for each and insert it in to a table takes 30 or 40 minutes.
What I would like is a single query that returns the top to values for all patients that wouldn't take for ever to run. I could then count where over 1 and get my cohort of patients.
Is this possible and can anyone point me in the right direction.
Greg
I can group on Patient_ID and count the number of values that are over the threshold, but that does not really account for only the last 2 values. It could be the 1st and the 3rd or the 7th and 15th.
Code:
SELECT tblAllHTNPatients.PatientID, Count(tblVital.[Value ]) AS HighBP
FROM tblAllHTNPatients INNER JOIN tblVital ON tblAllHTNPatients.PatientID = tblVital.PatientID
WHERE (((tblVital.[Value ])>160) AND ((tblVital.EncounterDate)>=#1/1/2010#) AND ((tblVital.ItemName)="Systolic Blood Pressure"))
GROUP BY tblAllHTNPatients.PatientID
HAVING (((Count(tblVital.[Value ]))>1));
Code:
SELECT Q.PatientID INTO tblHTNReportPatients
FROM tblVital INNER JOIN (
SELECT tblAllHTNPatients.PatientID, tblVital.ItemName,
Max(tblVital.EncounterDate) AS MaxEncDate
FROM tblAllHTNPatients INNER JOIN tblVital
ON tblAllHTNPatients.PatientID = tblVital.PatientID
WHERE (((tblVital.EncounterDate)>=#1/1/2010#) AND ((tblVital.ItemName)="Systolic Blood Pressure"))
GROUP BY tblAllHTNPatients.PatientID, tblVital.ItemName
) AS Q
ON (tblVital.EncounterDate = Q.MaxEncDate) AND
(tblVital.ItemName = Q.ItemName) AND
(tblVital.PatientID = Q.PatientID)
WHERE (((tblVital.[Value ])>160));
The problem is, this takes for ever. It is only 600 patients, but running a TOP 2 query for each and insert it in to a table takes 30 or 40 minutes.
What I would like is a single query that returns the top to values for all patients that wouldn't take for ever to run. I could then count where over 1 and get my cohort of patients.
Is this possible and can anyone point me in the right direction.
Greg