如何获取 SQL Server 中两个日期之间所有周的开始和结束日期?
问题描述:
我需要获取两个日期之间的所有周开始和结束日期(周),然后运行查询返回每个周插入的记录数.
I need to get all week start and end dates(weeks) between two dates and then run a query returning the number of records inserted in each of those weeks.
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
答
您可以使用递归 CTE 来生成日期列表:
You can use a recursive CTE to generate the list of dates:
;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
然后您可以将其加入您的表,以返回其他详细信息.
Then you can join this to your table, to return the additional details.