Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
stevenandler
Starting Member
42 Posts |
Posted - 2012-10-10 : 15:57:26
|
I am trying to create a select query that will pull the latest record for each patient only. For instance, if the table has the following rows:PATIENT_ID MRN LASTNAME FIRSTNAME1234 6767 BROWN CHARLIE2345 6767 BROWN CHARLIE3456 6767 BROWN CHARLIE I would like my select statement to return only the third row. I don't think the Distint Key word can work in this scenario because there are other columns with different date and time stamps for each row. |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-10-10 : 16:16:13
|
quote: Originally posted by stevenandler I am trying to create a select query that will pull the latest record for each patient only. For instance, if the table has the following rows:PATIENT_ID MRN LASTNAME FIRSTNAME1234 6767 BROWN CHARLIE2345 6767 BROWN CHARLIE3456 6767 BROWN CHARLIE I would like my select statement to return only the third row. I don't think the Distint Key word can work in this scenario because there are other columns with different date and time stamps for each row.
Is that [MRN] column the patient identifier? Your [PATIENT_ID] values are different for each Charlie Brown.But at any rate one way is to identify which of your date columns represents the sequence of which you want the "last" row. Then select the max(<date>) grouped by a patient identifier. Then turn that statement into a derived table and join to the main table by patient identifier and that date column.ie:select yt.*from ( select patient_id, max(dt) as dt from yourTable ) djoin youTable yt on yt.patient_id = d.patient_id and yt.dt = d.dt Be One with the OptimizerTG |
|
|
stevenandler
Starting Member
42 Posts |
Posted - 2012-10-10 : 16:35:59
|
My apology. I didn't provide enough infomation.The primary keys for the table OGEN.GEN_M_PATIENT_MAST areFACILITY_KEY AND PATIENT_ID. I am trying to perform a select from this table by specifying the FACILITY_KEY in a where statement. Since the table contains many rows with the same patient, I am trying to retrive only the latest entry which can be determined by the PATIENT_ID number. The higher the number, the more recent the entry. |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-10-10 : 17:44:24
|
>>The higher the number, the more recent the entry.Then use that number instead of [dt] in my example. If you still need help then post actual DDL and a few rows of DML.Be One with the OptimizerTG |
|
|
|
|
|