How to get week number of the month from the date in sql server 2008

后端 未结 22 1821
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:52

In SQL Statement in microsoft sql server, there is a built-in function to get week number but it is the week of the year.

Select DatePart(week, \'2012/11/30\         


        
相关标签:
22条回答
  • 2020-11-27 16:41

    Here is the tried and tested solution for this query in any situation - like if 1st of the month is on Friday , then also this will work -

    select (DATEPART(wk,@date_given)-DATEPART(wk,dateadd(d,1-day(@date_given),@date_given)))+1
    

    above are some solutions which will fail if the month's first date is on Friday , then 4th will be 2nd week of the month

    0 讨论(0)
  • 2020-11-27 16:42
    floor((day(@DateValue)-1)/7)+1
    
    0 讨论(0)
  • 2020-11-27 16:42

    Here you go....

    Im using the code below..

    DATEPART(WK,@DATE_INSERT) - DATEPART(WK,DATEADD(DAY,1,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@DATE_INSERT),0)))) + 1
    
    0 讨论(0)
  • 2020-11-27 16:44

    Solution:

    declare @dt datetime='2018-03-31 05:16:00.000'
    IF (Select (DatePart(DAY,@dt)%7))>0
    Select  (DatePart(DAY,@dt)/7) +1
    ELSE
    Select  (DatePart(DAY,@dt)/7)
    
    0 讨论(0)
  • 2020-11-27 16:44

    Logic here works as well 4.3 weeks in every month. Take that from the DATEPART(WEEK) on every month but January. Just another way of looking at things. This would also account for months where there is a 5th week

    DECLARE @date VARCHAR(10)
    SET @date = '7/27/2019'
    
    SELECT CEILING(DATEPART(WEEK,@date)-((DATEPART(MONTH,@date)-1)*4.3333)) 'Week of Month'
    
    0 讨论(0)
  • 2020-11-27 16:44

    Code is below:

    set datefirst 7
    declare @dt datetime='29/04/2016 00:00:00'
    select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7
    
    0 讨论(0)
提交回复
热议问题