How to find the Nearest (day of the week) for a given date

后端 未结 3 616
长情又很酷
长情又很酷 2021-01-22 18:32

I been practicing queries, and my current scenario is to find the nearest Saturday for a given date. After i got the logic down, i came up with a, whats looks like a long and me

3条回答
  •  隐瞒了意图╮
    2021-01-22 19:04

    Try this:

    select dateAdd(dd,7-DATEPART(dw,getDate()),GETDATE())
    

    datePart(dw,...) returns day of the week for current date.

    7 - that number, returns number of days until Saturday

    Add the result to the date to get the next Saturday...

    Similar logic if you need to go back to previous Saturday

    Sql Fiddle: http://www.sqlfiddle.com/#!3/61998/2

提交回复
热议问题