Get the most recent Friday's date SQL

后端 未结 8 1220
孤城傲影
孤城傲影 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:30

    Using a known Friday date (I'll use Jan 7, 2011) as a starting point, you can do this:

    DECLARE @d DATETIME
    
    SET @d = '2011-05-13' /* Friday */
    SELECT DATEADD(DAY, (DATEDIFF (DAY, '20110107', @d) / 7) * 7, '20110107')
    /* Returns 2011-05-13 */
    
    SET @d = '2011-05-12' /* Thursday */
    SELECT DATEADD(DAY, (DATEDIFF (DAY, '20110107', @d) / 7) * 7, '20110107')
    /* Returns 2011-05-06 */
    

    Just choose a known Friday that's older than any dates you'll be using in your calculations.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题