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

后端 未结 22 1915
没有蜡笔的小新
没有蜡笔的小新 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:35

    Here's a suggestion for getting the first and last days of the week for a month:

    -- Build a temp table with all the dates of the month 
    drop table #tmp_datesforMonth 
    go
    
    declare @begDate datetime
    declare @endDate datetime
    
    set @begDate = '6/1/13'
    set @endDate = '6/30/13';
    
    WITH N(n) AS  
    (   SELECT 0  
            UNION ALL 
        SELECT n+1 
        FROM N 
        WHERE n <= datepart(dd,@enddate)
    )
    SELECT      DATEADD(dd,n,@BegDate) as dDate 
    into #tmp_datesforMonth
    FROM        N
    WHERE       MONTH(DATEADD(dd,n,@BegDate)) = MONTH(@BegDate)
    
    --- pull results showing the weeks' dates and the week # for the month (not the week # for the current month) 
    
    select  MIN(dDate) as BegOfWeek
    , MAX(dDate) as EndOfWeek 
    , datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate) as WeekNumForMonth 
    from #tmp_datesforMonth
    group by datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, dDate), 0)), 0), dDate) 
    order by 3, 1
    

提交回复
热议问题