Search code examples
sqlsql-server-2008-r2monthcalendar

Split month by week range (Monday-Friday) in SQL Server


I'm using SQL Server 2008R2 and I'm trying to split given month by week ranges. I got the following solution. But, I want days between (Mon-Fri) not (Sun-Sat). How can I do this?

DECLARE @start_date DATETIME, @end_date DATETIME
DECLARE @Table table(StartDate datetime,Enddate datetime,WeekNo int)

SET @start_date = '1 Dec 2018'
SET @end_date =   '31 Dec 2018'

INSERT @Table 
SELECT MIN(dt), MAX(dt), w
FROM
(
    SELECT dt, year(dt) y, DATEPART(week,dt) w
    FROM
    (
        SELECT @start_date + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1) dt
        FROM sys.columns s1 cross join sys.columns s2
    ) q
    WHERE dt BETWEEN @start_date AND @end_date
) a
group by y,w

Select * from @Table order by startdate, weekno

Solution

  • One option would be to generate only records and gets the monday dates between @start_date and @end_date

    After that ensure the boundary conditions are taken into account for

    DECLARE @start_date DATETIME, @end_date DATETIME
    DECLARE @Table table(StartDate datetime,Enddate datetime,WeekNo int)
    
    SET @start_date = '1 Nov 2018'
    SET @end_date =   '30 Nov 2018'
    
    set datefirst 1;
    
    INSERT @Table 
         SELECT dt as start_of_week
               ,dateadd(dd,4,dt) as end_of_week
               ,DATEPART(week,dt) w
               ,datepart(dw,q.dt)
          FROM
          (
            SELECT @start_date + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1) dt              
              FROM sys.columns s1 cross join sys.columns s2
           ) q
        WHERE dt BETWEEN @start_date AND @end_date
         AND datepart(dw,q.dt)=1 /*Gets only the days beginning from monday*/
         --AND dateadd(dd,4,q.dt) <= @end_date /*Ignore any records which cross over the @end_date*/
    
    Select * from @Table order by startdate, weekno