在 SQL 服务器中按周范围(周一至周五)拆分
Split month by week range (Monday-Friday) in SQL Server
我正在使用 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
一种选择是仅生成记录并获取@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
我正在使用 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
一种选择是仅生成记录并获取@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