8

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

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
4

2 回答 2

13

您可以使用递归 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

然后,您可以将其加入您的表中,以返回其他详细信息。

于 2013-02-25T16:19:28.130 回答
0

这是我的解决方案。受此答案启发

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
于 2021-03-12T03:52:56.653 回答