August 22, 2006 at 2:56 pm
I have two tables, one with Patients and one with Visits.
I need to select the latest Visit (all columns) for each Patient listed in tblPatients. I want one record for each Patient.
SELECT *
FROM tblVisit
INNER JOIN tblPatient ON tblVisit.ACCT = tblPatient.ACCT
Order BY ACCT ASC, SERV_DATE DESC
I tried DISTINCT and TOP.
I think I need DISTINCT per ACCT but I don't know how to code that. As you can tell, I am a rookie...not sure what I am doing.
August 22, 2006 at 2:59 pm
What is the data type of SERV_DATE ? Is it a true datetime ? Is it possible for a patient to have 2 visits in the same day, and could there ever be 2 records in tblVisit with the same SERV_DATE for the same patient ?
This is why posting table DDL and index/constraint definitions will usually get you a faster/more complete/more correct answer.
August 22, 2006 at 6:30 pm
Which visit "DISTINCT per ACCT" you want to see?
First? Last? First for today? Last before today?
If you include Visit into returned set and you want to see only one per ACCT you must choose one.
_____________
Code for TallyGenerator
August 23, 2006 at 2:21 am
Sergiy,
I think you overlooked this:
"I need to select the latest Visit (all columns) for each Patient listed in tblPatients. I want one record for each Patient."
That seems to be pretty straightforward, we just have to wait till rothjm supplies data structures and a sample, to see what "latest" means in this particular case...
August 23, 2006 at 6:53 am
If you have unique patient ID's and Visit ID's try something like this:
SELECT *
FROM tblPatient,
tblVisit,
(SELECT DISTINCT
PatientID,
MAX(VisitDate) AS LatestVisit
FROM tblVisit
GROUP BY PatientID) AS TEST
WHERE tblPatient.PatientID = TEST.PatientID
AND tblVisit.VisitDate = TEST.LatestVisit
AND tblPatient.PatientID = tblVisit.PatientID
ORDER BY ACCT ASC, SERV_DATE DESC
August 23, 2006 at 7:20 am
Yes it is a DateTime field.
There could be multiple records in the tblVisit but I do just want the latest record.
August 23, 2006 at 7:23 am
Yes there is a unique Patient MedRec# and then ACCT#'s for each visit. The ACCT#'s duplicate in tblVisit because there are multiple updates...like if they are moved to another bed etc.
I will try your example. Thanks!
August 23, 2006 at 9:15 am
DavidP,
Your code pulls the data I want...except...I don't want the columns from tblPatient.
I only want the fields from tblVisit.
Any ideas how to do that?
Thanks
August 23, 2006 at 9:16 am
I think I figured it out.
Instead of: SELECT *
I did: SELECT tblVisit.*
I got it to work! Thanks for all your advice!
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply