如何获取 SQL Server 中两个日期之间所有周的开始和结束日期? [英] how to get the start and end dates of all weeks between two dates in SQL server?

查看:44
本文介绍了如何获取 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

参见SQL Fiddle with Demo.

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

Then you can join this to your table, to return the additional details.

这篇关于如何获取 SQL Server 中两个日期之间所有周的开始和结束日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆