Get the most recent Friday's date SQL

后端 未结 8 1228
孤城傲影
孤城傲影 2021-02-13 00:48

I\'m trying to get the most recent Friday in SQL Server 2008.

I have this. It gets the beginning of the week (monday) then subtracts 3 days to get Friday.



        
8条回答
  •  一向
    一向 (楼主)
    2021-02-13 01:31

    This works for any input and any setting of DATEFIRST:

    dateadd(d, -((datepart(weekday, getdate()) + 1 + @@DATEFIRST) % 7), getdate())
    

    It works by adjusting the weekday value so that 0 = Friday, simulating Friday as the beginning of the week. Then subtract the weekday value if non-zero to get the most recent Friday.

    Edit: Updated to work for any setting of DATEFIRST.

提交回复
热议问题