Numbers of weekdays in a date range in TSQL

后端 未结 4 1972
忘了有多久
忘了有多久 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:32

    An alternative approach is the good old-fashioned data warehouse time dimension, where you have a table with all potential dates in it, along with any useful information you want to filter/count by:

    Key       ActualDate  DayName   IsWeekday  DayNumberInYear  FinancialQuarter
    20110101  1 Jan 2011  Saturday  0          1                2011 Q1
    20110102  2 Jan 2011  Sunday    0          2                2011 Q1
    20110103  3 Jan 2011  Monday    1          3                2011 Q1
    

    Then just join to that table and filter, e.g.

    SELECT 
      COUNT(*) 
    FROM 
      date_dimension
    WHERE
      ActualDate BETWEEN '1 Jan 2011' AND '3 Jan 2011' AND
      IsWeekday = 1
    

    If you do date analysis a lot over a known range of dates, this can really speed up and simplify your queries. Whether you know your possible date ranges in advance is the limiting factor on whether this is helpful, really, but it's a useful trick to know about.

提交回复
热议问题