简体   繁体   中英

Many to many join with filter

I have two tables like so -

Table 1 -

patient   admit_dt     discharge_dt
323       2020-01-09   2020-02-01
323       2020-02-18   2020-02-27
231       2020-02-13   2020-02-17

Table 2 -

patient   admit_dt     discharge_dt
323       2020-02-05   2020-02-07
231       2020-02-23   2020-02-28

The output I am needing is

patient   
323  

The logic is - if one patient goes from table 1 into table 2 and ends up back in table 1 within 30 days, we want to count them in the output.

Patient 231 is not included in the result because they didn't go back to table 1 .

If I understand correctly, you can use join :

select t1.patient
from table1 t1 join
     table2 t2
     on t2.patient = t1.patient and
        t2.admit_dt > t1.discharge_dt join
     table1 tt1
     on tt1.patient = t1.patient and
        tt1.admit_dt > t2.discharge_dt;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM