I am looking for a SQL query.
Table 1: Source Table
Table 2: Result Table
Attached the patient table. Here I want to find the Highest Score, Highest Score Date, Lowest Score and Lowest Score Date of each patient. The tricky part is that if a patient has same highest score (here it is 9) on two different dates (10/5/2018 and 8/4/2020), we need to take earliest high score (10/5/2018). Similarly, if the patient has same lowest score (6 here) on two different dates (3/1/2019 and 4/2/2020) we should take the latest low score (4/2/2020)
Table 1: Source table contains all scores of a single patient. Patient ID is the primary key of that table. I want a result table that look like table 2.
I have tried this
SELECT distinct
pat.PAT_NAME 'Patient Name'
, pat.PAT_ID
, CAST(pat.CONTACT_DATE AS DATE) 'Service Date'
, pat.MEAS_VALUE 'Score'
, [Row Number] = rank() OVER (PARTITION BY pat.PAT_ID ORDER BY CAST(pat.MEAS_VALUE AS int) DESC, CONTACT_DATE asc)
FROM Patient pat
WHERE pat.PAT_ID = 'A112233'
But this code can show me highest or the lowest score. But it does not meet all my requirement.
Advertisement
Answer
If there is table t with columns: PatientName, PatientID, ServiceDate, Score. Something like this:
;with high_low_cte(PatientID, high_rn, low_rn) as(
select
PatientID,
row_number() over (partition by PatientID order by Score, ServiceDate asc),
row_number() over (partition by PatientID order by Score, ServiceDate desc)
from
t)
select * from high_low_cte where high_rn=1 and low_rn=1;
After update to question:
;with high_low_cte([Patient Name], PAT_ID, [Service Date], Score, high_rn, low_rn) as (
SELECT distinct
pat.PAT_NAME 'Patient Name'
,pat.PAT_ID
,CAST(pat.CONTACT_DATE AS DATE) 'Service Date'
,pat.MEAS_VALUE 'Score'
,high_rn=row_number() OVER (PARTITION BY pat.PAT_ID ORDER BY CAST(pat.MEAS_VALUE AS int) DESC, CONTACT_DATE asc)
,low_rn=row_number() OVER (PARTITION BY pat.PAT_ID ORDER BY CAST(pat.MEAS_VALUE AS int) asc, CONTACT_DATE asc)
FROM
Patient pat
WHERE
pat.PAT_ID='A112233')
select hld1.*, hld2.Score [Low_Score], hld2.[Service Date] [Low Service Date]
from high_low_cte hld1 join high_low_cte hld2 on hld1.PAT_ID=hld2.PAT_ID
where
hld1.high_rn=1
and hld2.low_rn=1;