Get the most recent Friday's date SQL

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

    DECLARE @date DATETIME = '20110512' -- Thursday
    SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',@date)%7),@date) --20110506
    
    SET @date = '20110513' -- Friday
    SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',@date)%7),@date) --20110513
    
    SET @date = '20110514' -- Saturday
    SELECT DATEADD(DAY,-(DATEDIFF(DAY,'19000105',@date)%7),@date) --20110513
    
    1. Calculate the number of days between a known Friday (05 Jan 1900) and the given date
    2. The remainder left from dividing the difference in 1. by 7 will be the days elapsed since the last Friday
    3. Subtract the remainder in 2. from the given date

提交回复
热议问题