在SQL Server中按月范围(星期一至星期五)拆分月份

时间:2018-12-06 06:35:38

标签: sql sql-server-2008-r2 monthcalendar

我正在使用SQL Server 2008R2,并且试图按星期划分给定的月份范围。我得到以下解决方案。但是,我希望(星期一至星期五)到(星期日至星期六)之间的日子。我该怎么办?

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

1 个答案:

答案 0 :(得分:1)

一种选择是仅生成记录并获取@start_date和@end_date之间的星期一日期

在那之后确保考虑边界条件

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