This is harder than it looks. I need a function that calculates the numbers of a given weekday in a date range. I don\'t want any loops or recursive SQL. There are millions
This is what I came up with after trying alot of different approches. I did spend a long time on solving it and I was still working on it, when I posted the question. I decided to post it as an answer because of the self-learner badge, although I never got more than 2 points for an answer.
alter function dbo.f_countweekdays
( @day int, @fromdate datetime, @todate datetime )
returns int
begin
RETURN (SELECT datediff(day, @fromdate, dateadd(week,datediff(week,0,@todate - 1) +
CASE WHEN datepart(weekday,@todate) < @day THEN 0 ELSE 1 END,0) + @day - 1) / 7)
end