Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of fridays between two dates

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

like image 416
ssahu Avatar asked Feb 11 '11 10:02

ssahu


1 Answers

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
like image 137
Tony Andrews Avatar answered Oct 10 '22 05:10

Tony Andrews