给出一个周数,在T-SQL中返回一周的第一天

时间:2016-07-27 14:30:08

标签: sql sql-server tsql date

这将根据日期给我一个星期编号:

SELECT DATEPART(wk, '7/27/2016') AS [Week]

例如,返回31。

现在,我需要做的是找到那周的第一天,并以短日期格式返回。例如:

Given Week: 31
Return First Day of Week: July 24

或者

Given Week: 52
Return First Day of Week: Dec 25

我相信一周的默认第一天是星期日,那是我需要的日期。

我在这里看到了几篇贴近的帖子,但没有一个让我一路走来。

谢谢!

3 个答案:

答案 0 :(得分:1)

我帮助从内到外阅读。我添加了编号的评论来帮助。

declare @weekNum int;set @weeknum = 52;
select 
-- 3.  Add number of weeks
dateadd(wk, @weekNum, 
    --2.  first day of week 0 for that year (may belong to previous year)
    dateadd(ww, datediff(wk, 0, 
        --1.  First date of the year (week 0)
        dateadd(YEAR, datediff(year,0, getDate()),0)
     ),-1) -- -1 here because 1900-01-01 (date 0) was a Monday, and adding weeks to a Monday results in a Monday.
)

我们可以将第二步和第三步结合起来,因为它们都会增加几周:

declare @weekNum int;set @weeknum = 52;
select 
    --2.  first day of week 0 for that year (may belong to previous year) + number of weeks
    dateadd(ww, @weekNum + datediff(wk, 0, 
        --1.  First date of the year (week 0)
        dateadd(YEAR, datediff(year,0, getDate()),0)
     ),-1) -- -1 here because 1900-01-01 (day 0) was a Monday. Adding weeks to a Monday results in a Monday

另外,我认为你第31周的例子已经过了一周。你可以看到这一年的全套:

with weeks as 
(
    select top 52 row_number() over (order by  object_id) as wk  from sys.objects
)
select wk,
    --2.  first day of week 0 for that year (may belong to previous year) + number of weeks
    dateadd(ww, wk + datediff(wk, 0, 
        --1.  First date of the year (week 0)
        dateadd(YEAR, datediff(year,0, getDate()),0)
     ),-1) -- -1 here because 1900-01-01 (day 0) was a Monday. Adding weeks to a Monday results in a Monday
from weeks

答案 1 :(得分:1)

以下是使用DATEDIFF和DATEADD的示例(第3行是获取您要查找的值的一行代码)。这可能与接受的答案类似。

我发帖是因为这是我在为自己记录时在函数中使用的分解。

--1. Get the number of Weeks since Monday, January 1, 1900
select DATEDIFF(wk, 0, '01/01/2016') -- 6052 Weeks

--2: Take the value since 1900 + Number of Weeks - 8 Days get you to Sunday.
select DATEADD(wk, 6052 + (31), -8);

--3. Put it all together..
select DATEADD(wk, DATEDIFF(wk, 0, '1/1/2016' ) + (31), -8); --=2016-07-24

答案 2 :(得分:0)

看看我的计算。这个想法是从今年1月1日开始,并从那里开始算术。

declare @year int=2016, @wk int=31
--A) Single chain calculations
select case datepart(weekday,cast(concat(@year,'-01-01') as date))
            when 1 then dateadd(wk,@wk-1,cast(concat(@year,'-01-01') as date))
            else dateadd(wk,@wk-1,
                  dateadd(day, 1/*8 if you want "first full week"*/ - datepart(weekday, cast(concat(@year,'-01-01') as date)),
                          cast(concat(@year,'-01-01') as date))) end

--B) the same in a better readable form    
;with tmp as (
select  cast(concat(@year,'-01-01') as date) jan01
)
select case datepart(weekday,jan01)
            when 1 then dateadd(wk, @wk-1, jan01)
            else dateadd(wk, @wk-1, dateadd(day, 1 - datepart(weekday, jan01), jan01)) end frstDay
from tmp