如何获取SQL Server中两个日期之间所有周的开始和结束日期?

时间:2013-02-25 16:14:24

标签: sql-server tsql

我需要获取两个日期之间的所有星期开始和结束日期(星期),然后运行一个查询,返回每个星期中插入的记录数。

declare @sDate datetime,
        @eDate datetime;

select  @sDate = '2013-02-25',
        @eDate = '2013-03-25';

--query to get all weeks between sDate and eDate

--query to return number of items inserted in each of the weeks returned



WEEK                  NoOfItems
-----------------------------------------
2013-02-25            5
2013-03-4             2
2013-03-11            7

2 个答案:

答案 0 :(得分:11)

您可以使用递归CTE生成日期列表:

;with cte as
(
  select @sDate StartDate, 
    DATEADD(wk, DATEDIFF(wk, 0, @sDate), 6) EndDate
  union all
  select dateadd(ww, 1, StartDate),
    dateadd(ww, 1, EndDate)
  from cte
  where dateadd(ww, 1, StartDate)<=  @eDate
)
select *
from cte

请参阅SQL Fiddle with Demo

然后你可以将它加入你的桌子,以返回其他细节。

答案 1 :(得分:0)

这是我的解决方案。灵感来自 this 答案

DECLARE @sDate DATE = DATEADD(MONTH, -6, GETDATE())
DECLARE @eDate DATE = GETDATE()
;WITH cte AS
(
  SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, @sDate), 0) AS StartDate, DATEADD(WEEK, DATEDIFF(WEEK, 0, @sDate), 6) AS EndDate
  UNION ALL
  SELECT DATEADD(WEEK, 1, StartDate), DATEADD(WEEK, 1, EndDate)
  FROM cte
  WHERE DATEADD(WEEK, 1, StartDate) <= @eDate
)

SELECT * FROM cte