Number of fridays between two dates

前端 未结 7 1904
我寻月下人不归
我寻月下人不归 2020-12-06 06:58

How do I find the number of fridays between two dates(including both the dates) using a select statement in oracle sql?

7条回答
  •  清歌不尽
    2020-12-06 07:40

    This will do it:

    select ((next_day(date2-7,'FRI')-next_day(date-1,'FRI'))/7)+1 as num_fridays
    from data
    

    Perhaps best if I break that down. The NEXT_DAY function returns the next day that is a (Friday in this case) after the date.

    So to find the first Friday after d1 would be:

    next_day( d1, 'FRI')
    

    But if d1 is a Friday that would return the following Friday, so we adjust:

    next_day( d1-1, 'FRI')
    

    Similarly to find the last Friday up to and including d2 we do:

    next_day( d1-7, 'FRI')
    

    Subtracting the 2 gives a number of days: 0 if they are the same date, 7 if they a re a week apart and so on:

    next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI') 
    

    Convert to weeks:

    (next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7
    

    Finally, if they are the same date we get 0, but really there is 1 Friday, and so on so we add one:

    ((next_day( d1-7, 'FRI') - next_day( d1-1, 'FRI')) / 7) + 1
    

提交回复
热议问题