Calculate week of month starting Monday

前端 未结 2 871
無奈伤痛
無奈伤痛 2021-01-28 22:09

I have this function that works very well to calculate the week of month - i need it to start the week from Monday

CREATE FUNCTION dbo.ufs_FirstofMonth (@theDate         


        
相关标签:
2条回答
  • 2021-01-28 22:41

    Add the following as the first line in your functions:

    SET DATEFIRST 1 -- Set Monday as the first day of the week
    

    Ref. SET DATEFIRST (Transact-SQL) - Sets the first day of the week to a number from 1 through 7. The U.S. English default is 7, Sunday.

    0 讨论(0)
  • 2021-01-28 23:00

    Here are 2 different ways, both are assuming the week starts on monday

    If you want weeks to be whole, so they belong to the month in which they start: So saturday 2012-09-01 and sunday 2012-09-02 is week 4 and monday 2012-09-03 is week 1 use this:

    declare @date datetime = '2012-09-01'
    select datepart(day, datediff(day, 0, @date)/7 * 7)/7 + 1
    

    If your weeks cut on monthchange so saturday 2012-09-01 and sunday 2012-09-02 is week 1 and monday 2012-09-03 is week 2 use this:

    declare @date datetime = '2012-09-01'
    select datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @date), 0)), 0),     @date - 1) + 1
    
    0 讨论(0)
提交回复
热议问题