Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the most recent Friday's date SQL

Tags:

sql

sql-server

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.

declare @recentFriday datetime =  DATEADD(ww, DATEDIFF(dd,0,GETDATE()), 0)-3

When this is run during the week, it gets last Friday's date which is correct. But when run on Friday (or Saturday), it still gets last week's date instead of the current week's Friday. I'm about to use if/else conditions but I'm sure there's an easier way.

like image 292
James Avatar asked May 13 '11 21:05

James


People also ask

How do I get last Friday of the month in SQL?

I will be passing the year and month as parameter,e.g, 201211. If I pass '201211' as parameter it should return me '20121130' as answer as it's the date of last friday of month of november'12.

How do I get the current week Friday date in SQL?

MySQL WEEK() Function The WEEK() function returns the week number for a given date (a number from 0 to 53).

How do you find Friday in SQL?

The WEEKDAY() function returns the weekday number for a given date. Note: 0 = Monday, 1 = Tuesday, 2 = Wednesday, 3 = Thursday, 4 = Friday, 5 = Saturday, 6 = Sunday.


2 Answers

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.

like image 199
mellamokb Avatar answered Oct 01 '22 21:10

mellamokb


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
like image 39
Pero P. Avatar answered Oct 01 '22 21:10

Pero P.