简体   繁体   中英

SQL Count dates in one table that occur between a start and end date in another table

I have a table ' tb1 ' that looks like this:

Nurse    Start          End        Posting 
---    ------------   -----------  -------
123    2012-04-26     2014-02-10   ABC
123    2015-03-21     2016-01-12   DEF
123    2016-05-19     2018-09-14   MNO
256    2017-01-15     2018-02-20   JKL
256    2018-07-13     2019-01-17   MNO

And another separate table ' tb2 ' that can be linked to the above table by the column Nurse .

Nurse    PartyDate 
---    ------------  
123    2017-02-23     
123    2017-05-11     
256    2018-11-28

I want to count the number of parties that each Nurse attends between the start and end date of each posting. The expected result should look like this:

Nurse    Start          End        Posting   Count
---    ------------   -----------  -------   ------
123    2012-04-26     2014-02-10    ABC        0
123    2015-03-21     2016-01-12    DEF        0
123    2016-05-19     2018-09-14    MNO        2
256    2017-01-15     2018-02-20    JKL        0
256    2018-07-13     2019-01-17    MNO        1

One method is a correlated subquery:

select t1.*,
       (select count(*)
        from tb2 t2
        where t2.nurse = t1.nurse and
              t2.partydate >= t1.start and
              t2.partydate <= t1.end
       ) as num_parties
from tb1 t1;

For performance, you want an index on tb2(nurse, start, end) .

Here is another way of achieving this.

select tb1.nurse, tb1.start, tb1.end, tb1.posting, count(tb2.partydate) Count
from tb1 left join tb2 on (tb1.nurse = tb2.nurse 
                           and tb2.partyDate between tb1.start and tb1.end)
group by tb1.nurse, tb1.start, tb1.end, tb1.posting 
;

It is expected to run faster than the correlated queries as in the case of latter for every record from tb1 DB engine will have to scan through tb2 table

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