我需要获取两个日期之间的所有星期开始和结束日期(星期),然后运行一个查询,返回每个星期中插入的记录数。
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
答案 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
然后你可以将它加入你的桌子,以返回其他细节。
答案 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