-2

How to get previous friday in SQL Server?

Here is the code I have so far:

select (7 -datePart(dw, getdate()+3)) +1
JohnFx
  • 34,542
  • 18
  • 104
  • 162
Bharath T
  • 41
  • 1
  • 7

3 Answers3

2

Use mod like this:

declare @date datetime = getdate()
declare @dow int = datepart(dw,@date)
declare @mod int = @dow % 7 +1
select cast(dateadd(d,-@mod ,@date) as date)
Daniel Marcus
  • 2,686
  • 1
  • 7
  • 13
  • 1
    Tip: `( @@DateFirst + DatePart( weekday, SampleDate ) - 1 ) % 7 + 1` will always return an integer from `1` to `7` with `1` corresponding to Sunday regardless of the setting of `DateFirst` or `Language`. – HABO Jun 16 '18 at 03:02
0

If your week starts on Sunday, then here's a one-liner:

SELECT DATEADD(WEEK
              ,DATEDIFF(WEEK, '1900-01-05', DATEADD(DAY, 6 - DATEPART(DAY, GETDATE()) - 1, GETDATE()))
              ,'1900-01-05') AS [Last Friday]

The query counts the number of weeks since 1900-01-05 (which is a Friday) to today's date minus 1 week. This number of weeks is added to 1900-01-05 to get the previous week's Friday.

Zorkolot
  • 1,899
  • 1
  • 11
  • 8
0

Try this select convert(varchar(10), DATEADD(DD, -1 - DATEPART(DW, CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE()))) ),CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE())))),101) It will give you previous friday of every week

maddy
  • 50
  • 1
  • 1
  • 10