Sql server 在SQL Server中获取从星期日到星期六的周周期

Sql server 在SQL Server中获取从星期日到星期六的周周期,sql-server,Sql Server,我需要一份特定月份和年份的周数清单。显示每周的初始和最终日期 它必须在星期天开始,星期六结束 示例:2018年第10个月: 请注意,结束日期可能超过月份,因为您应该考虑开始日期是选定月份的一部分。 < P>此查询将起作用。p> ;with w as ( select convert(date,'2018-10-01') as startdate, convert(date,'2018-10-01') as dt union all select startdate, dateadd(d,1,dt

我需要一份特定月份和年份的周数清单。显示每周的初始和最终日期

它必须在星期天开始,星期六结束

示例:2018年第10个月:

请注意,结束日期可能超过月份,因为您应该考虑开始日期是选定月份的一部分。

< P>此查询将起作用。p>
;with w as (
select convert(date,'2018-10-01') as startdate, convert(date,'2018-10-01') as dt
union all
select startdate, dateadd(d,1,dt) from w where month(startdate)=month(dateadd(d,1,dt))
) 
select row_number() over (order by dt) as wk, 
    dt as wkstart, 
    dateadd(d,6,dt) as wkend 
from w 
where datediff(d,convert(date,'2018-10-07'),dt)%7=0
结果:

wk  wkstart     wkend
1   2018-10-07  2018-10-13
2   2018-10-14  2018-10-20
3   2018-10-21  2018-10-27
4   2018-10-28  2018-11-03

编辑:我改变了周日被认为与语言无关的方式。

日期优先默认值实际上取决于语言。所以不必总是默认为7个星期天谢谢你的回复。但结束日期必须是星期六。我试图在这里确定我可以在您的QueryTanks@Squirrel中更改此项的位置-我将where子句更改为语言不可知。然后将结束日期改为dt+6,所以这是周六而不是下周日。好奇的是@TiagoMullerPereira为什么你更喜欢另一个答案。它们都做相同的事情,但这一个使用了更简单的算法。我使用了一个硬编码的开始日期“2018-10-01”作为例子,但在现实生活中,这显然会被一个变量所取代。对不起,我刚才看到了你的答案。这确实是最优雅的解决方案。谢谢你的支持,这正是我所需要的。非常感谢你。
declare @year   int, 
        @month  int

select  @year   = 2018,
        @month  = 10

; with 
-- get first and last day of the month
dates as
(
    select  first_of_mth = dateadd(year, @year - 1900, dateadd(month, @month - 1, 0)),
            last_of_mth = dateadd(year, @year - 1900, dateadd(month, @month, -1))
),
-- get first sunday of the month
dates2 as
(
    select  first_of_mth, last_of_mth,
            first_sun_of_mth = dateadd(week, datediff(week, 0, dateadd(day, 7 - datepart(day, first_of_mth), first_of_mth)), -1)
    from    dates
),
-- recursive CTE to get all weeks of the month
weeks as
(
    select  week_no     = 1, 
            begin_date  = first_sun_of_mth,
            end_date    = dateadd(day, 6, first_sun_of_mth),
            last_of_mth
    from    dates2

    union all

    select  week_no     = week_no + 1,
            begin_date  = dateadd(day, 7, begin_date),
            end_date    = dateadd(day, 7, end_date),
            last_of_mth
    from    weeks
    where   dateadd(day, 7, begin_date) <= last_of_mth
)
select  week_no, begin_date, end_date
from    weeks