How to calculate the number of “Tuesdays” between two dates in TSQL?

前端 未结 4 1683
[愿得一人]
[愿得一人] 2020-11-29 12:29

I\'m trying to figure out how to calculate the number of \"Tuesdays\" between two dates in TSQL?

\"Tuesday\"could be any value.

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 12:53

    @t-clausen.dk & Andriy M as response to t-clausen.dks response and comments

    The query uses the fact that 1900-01-01 was a monday. And 1900-01-01 is the date 0.

    select dateadd(day,0,0)

    The second parameter into the datediff-function is the startdate.

    So you are comparing '1899-12-26' with your @to-date and '1899-12-26' is a tuesday

    select datename(dw,dateadd(day, 0, -6)), datename(dw, '1899-12-26')

    Same thing about the second date that uses the same fact.

    As a matter of fact you can compare with any known tuesday and corresponding wednesday (that isnt in the date interval you are investigating).

    declare @from datetime= '2011-09-19' 
    declare @to datetime  = '2011-10-15' 
    
    select  datediff(day, '2011-09-13', @to)/7-datediff(day, '2011-09-14', @from)/7 as [works]
            ,datediff(day, '2011-10-18', @to)/7-datediff(day, '2011-10-19', @from)/7 as [works too]
            ,datediff(day, '2011-09-27', @to)/7-datediff(day, '2011-09-28', @from)/7 as [dont work]
    

    Basically the algorithm is "All Tuesdays minus all Wednesdays".

提交回复
热议问题