Calculating a simple number of particular days between two dates should NOT require a numbers table. Forcing I/O into a simple date calculation is not good practice.
You can do a simple calculation by figuring out the number of weeks between the two dates, and adjusting for where the desired day falls in relation to the end periods.
But I want to present another way to do it that actually allows you to specify any pattern of days you want to count. For example, it is just as easy to calculate the number of Saturdays and Sundays at once as it is to calculate the number of Mondays. I took pains to also make this query entirely independent of the SET DATEFIRST
setting.
DECLARE
@StartDate date = '2011-10-01',
@EndDate date = '2011-10-31';
WITH A AS (SELECT DayCount = DateDiff(day, @StartDate, @EndDate) + 1),
B AS (
SELECT
DayCount,
WeekCount = DayCount + 6 / 7,
Dow = DateDiff(day, '18991230', @StartDate) % 7 FROM A
)
SELECT
MondayCount =
Len(Replace(Substring(
Replicate('0100000', WeekCount),
Dow, DayCount
), '0', ''))
FROM B;
The trick is the string inside of the Replicate
function. It encodes Monday by placing a 1
in the second position (starting with Sunday as the first day).
You may feel repelled by such a string-munching solution as this--but I have played with this before and expect that you will find it very difficult to improve on its speed with regular date math (especially the part about being able to calculate for multiple days at once).