Numbers of weekdays in a date range in TSQL

后端 未结 4 1997
忘了有多久
忘了有多久 2021-01-06 07:07

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

4条回答
  •  醉酒成梦
    2021-01-06 07:29

    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
    

提交回复
热议问题