Reputation: 95
I want to select the details of patient discharged on 2015-03-16 from discharge table and their corresponding admission details from admission table.
discharge table
admission table
these are the two table which is used in query.the row marked with red must be selected using query.
Query used:
SELECT a.pat_id, a.pat_name, b.admit_date, b.admit_time, b.diagnosis,
b.Dr_name, a.dis_date, a.dis_time
from discharge_details a , admission_Details b
where dis_date = Convert(Date, DATEADD(day, -1, GETDATE()))
and a.pat_id = b.patient_id
and b.Admit_status = 'discharged'
Output obtained:
Required output:
Please... help me with your suggestion to modify my query.
Upvotes: 1
Views: 102
Reputation: 5636
A few suggestions, if I may:
With all that in mind, the way the tables are designed, you have to match a discharge record with the latest admission record for the patient that preceded the discharge -- and hope there were not two admissions on the same day. If that happens, you would need to get the time field in play and that complicates the query.
declare
@DischargeDate datetime;
set @DischargeDate = '2015-03-16';
select ad.Patient_ID, ad.Patient_Name, ad.Admit_Date, ad.Diagnosis,
ad.Dr_Name, dd.Dis_Date
from Discharge_Details dd
join Admission_Details ad
on ad.Patient_ID = dd.Pat_ID
and ad.Admit_Date =(
select Max( Admit_Date )
from Admission_Details
where Patient_ID = dd.Pat_ID
and Admit_Date < dd.dis_date)
where dd.Dis_Date >= @DischargeDate
and dd.Dis_Date < DateAdd( day, 1, @DischargeDate );
Upvotes: 1
Reputation: 8892
You can use the ROW_NUMBER() to get what you want. Since your Admit_Date
gives the reason to believe that which row might be first and which one is last that's why add order by
that.
SELECT
data.*
FROM
(
SELECT
*, ROW_NUMBER() OVER(PARTITION BY pat_id ORDER BY admit_Date desc) as rn
FROM
table
) as data
WHERE
data.rn = 1
ORDER BY data.pat_id
CREATE TABLE #temp
(id int,pat_id varchar(200), admit_Date date)
INSERT into #temp
values
(1,'pat_123','2015-03-12'),
(2,'pat_245','2015-03-16'),
(3,'pat_123 ','2015-03-16')
The above query gives me,
id pat_id admit_date rn
3 pat_123 2015-03-16 1
2 pat_245 2015-03-16 1
Upvotes: 3
Reputation: 35780
OUTER APPLY
s are perfect in scenarios like this:
SELECT a.pat_id ,
a.pat_name ,
b.admit_date ,
b.admit_time ,
b.diagnosis ,
b.Dr_name ,
a.dis_date ,
a.dis_time
FROM discharge_details a
OUTER APPLY (SELECT TOP 1 * FROM admission_Details d WHERE a.pat_id = d.patient_id AND d.Admit_status = 'discharged' ORDER BY admit_date desc )b
WHERE a.dis_date = CONVERT(DATE, DATEADD(DAY, -1, GETDATE()))
Upvotes: 1