如何在我的情况下使用SQL Server获取周数的开始日期和结束日期?

时间:2017-09-12 21:03:41

标签: sql sql-server date stored-procedures week-number

我已经找到获得周数,但是,它以不同的方式显示日期。

实际上当我检查

日期的周数时
select datepart(wk,'2016-01-02')  //Saturday

output: 1

select datepart(wk,'2016-01-03')  //Sunday

output: 2

但是当我使用周数得到开始和结束日期的日期时,它显示不同。

DECLARE @weekStart INT
DECLARE @weekEnd INT
DECLARE @Year INT

set @weekStart = 1
set @Year = 2016

DECLARE @WeekStartDate date
DECLARE @WeekEndDate date

SET @WeekStartDate = convert(date,DATEADD (WEEK, @weekStart, DATEADD (YEAR, @Year-1900, 0)) - 4 -
                                                DATEPART(DW, DATEADD (WEEK, @weekStart, DATEADD (YEAR, @Year-1900, 0)) - 4) + 1)
SET @WeekEndDate =convert(date,DATEADD (WEEK, @weekStart+1, DATEADD (YEAR, @Year-1900, 0)) - 4 -
                                                DATEPART(DW, DATEADD (WEEK, @weekStart+1, DATEADD (YEAR, @Year-1900, 0)) - 4) + 1)

select @WeekStartDate,@WeekEndDate


output: 
  StartingDate    EndingDate
  --------------------------
  2016-01-03      2016-01-09
  

我期待输出是,如果我给予周= 1,它应该给出 StartingDate = ** 2016-01-01和** EndingDate = 2016-01-02

     

对于第2周,它应该给出2016-01-03 2016-01-09

2 个答案:

答案 0 :(得分:1)

您可以获得本周的绝对开始/结束,然后调整当前年度的第一周开始和最后一周结束。你只需要计算开始,因为结束是开始+ 6天:

create procedure spWeekDates @year int, @week int
as
declare @firstWeekDay int
declare @yearStart datetime, @weekStartDate datetime, @weekEndDate datetime

set datefirst 7 -- change as needed
set @yearStart=cast(@year as char(4))+'0101' -- years always start on 01/01 [citation needed]
set @firstWeekDay=datepart(weekday,@yearStart)

-- absolute start/end dates
set @weekStartDate=dateadd(week,@week-1,@yearStart)-@firstWeekDay+1
set @weekEndDate=dateadd(day,6,@weekStartDate)
-- adjusting for target year
if year(@weekStartDate)<@year set @weekStartDate=@yearStart
if year(@weekEndDate)>@year set @weekEndDate=cast(@year as char(4))+'1231'

select @weekStartDate as WeekStartDate, @weekEndDate as WeekEndDate
go

exec spWeekDates 2016,1
exec spWeekDates 2016,2
exec spWeekDates 2016,53
go

结果:

|       WeekStartDate |         WeekEndDate |
|---------------------|---------------------|
| 2016-01-01 00:00:00 | 2016-01-02 00:00:00 |

|       WeekStartDate |         WeekEndDate |
|---------------------|---------------------|
| 2016-01-03 00:00:00 | 2016-01-09 00:00:00 |

|       WeekStartDate |         WeekEndDate |
|---------------------|---------------------|
| 2016-12-25 00:00:00 | 2016-12-31 00:00:00 |

答案 1 :(得分:0)

你必须得到第一年的一周中的一天 如果它不等于1那么你必须set @weekStart = @weekStart -1
set @StartingDate = first day in year