简体   繁体   中英

How to get start date and end date by selecting week number in SQL Server

I face a scenario where I have to get the start day and end day of a particular Week Number. The week day starts with Saturday and Ends Thursday.

Suppose I give a week number 40, output will be start date 26th Sept 2020 and end date will be 01st October.

I use

set datefirst 6 
select datepart(week, getdate()) WeekNo

to find out the week number - week starts from Saturday.

In addition to a week number, you will need to include a year number:

declare @wk int  set @wk = 40
declare @yr int  set @yr = 2020

select dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4 -
       datepart(dw, dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4) + 1 StartDate,
    dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4 -
       datepart(dw, dateadd (week, @wk-1, dateadd (year, @yr-1900, 0)) - 4) + 6 EndDate

StartDate               EndDate
2020-09-26 00:00:00.000 2020-10-01 00:00:00.000

Slightly modified from this great answer: SQL Convert Week Number to Date (dd/MM)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM