Skip to content
Advertisement

Filter on Rows that are Within a Certain Timeframe

I have a table of patients that were admitted and discharged from the hospital. I am trying to find any patients that have an admission within 30 days of their previous discharge date. So for example, I have the table:

Name Admission Date Discharge Date
Patient A 1/1/2021 1/5/2021
Patient A 1/7/2021 1/10/2021
Patient B 2/1/2021 2/4/2021

Then I would want to have a table of:

Name
Patient A

I am unsure of how to check the Discharge Date in row 1 against the Admission Date in row 2. I am using Microsoft SQL Server.

Advertisement

Answer

You can use lag():

select t.*
from (select t.*,
             lag(discharge_date) over (partition by name order by admission_date) as prev_discharge_date
      from t
     ) t
where prev_prev_discharge_date > dateadd(day, -30, admission_date)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement