Get the most recent Friday's date SQL

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.


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

you can check if the current day of week is friday or greater DATEPART(dw,GETDATE()) and then call (SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)+4) or (SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)-3)

SELECT 
CASE WHEN DATEPART(dw,GETDATE()) >= 5 THEN 
(SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)+4) 
ELSE 
(SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)-3) 
END

Tags:

Sql

Sql Server