在SQL Server中获取从星期日到星期六开始的一周时间

时间:2018-10-03 00:43:36

标签: sql-server

我需要获取特定月份和年份的周列表。显示每周的初始日期和最终日期。

它必须在星期日开始,并在星期六结束。

例如:对于2018年10月份:

Result

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

2 个答案:

答案 0 :(得分:1)

此查询将起作用。

;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

编辑:我更改了发现星期日与语言无关的方式。

答案 1 :(得分:0)

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