Get the most recent Friday's date SQL

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

    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
    
    0 讨论(0)
  • 2021-02-13 01:19

    The other solutions were not working for my use case.

    This works for finding any previous day by replacing 'Sunday' with the day you`re looking for:

        DECLARE @myDate DATE = GETDATE()
    
        WHILE DATENAME(WEEKDAY, @myDate) <> 'Sunday'
        BEGIN
            SET @myDate = DATEADD(DAY, -1, @myDate)
        END
    
    0 讨论(0)
  • 2021-02-13 01:20
    SELECT CONVERT(VARCHAR(12),GETDATE()) AS Today,
    CASE WHEN (DATEPART(DW,GETDATE())< 7) 
    THEN CONVERT(VARCHAR(12),(DATEADD(dd,-(DATEPART(DW,GETDATE())+1),GETDATE())))
    ELSE CONVERT(VARCHAR(12),(DATEADD(d,- 1,GETDATE())))
    END AS [Last Friday]
    
    0 讨论(0)
  • 2021-02-13 01:22

    Here is a completly set oriented way to achive the last Friday:

    select Friday from
    (
    select max(GetDate()) as Friday where datepart(dw, getdate()) = 6
    union all
    select max((GetDate() - 1)) where datepart(dw, (getdate() - 1)) = 6
    union all
    select max((GetDate() - 2)) where datepart(dw, (getdate() - 2)) = 6
    union all
    select max((GetDate() - 3)) where datepart(dw, (getdate() - 3)) = 6
    union all
    select max((GetDate() - 4)) where datepart(dw, (getdate() - 4)) = 6
    union all
    select max((GetDate() - 5)) where datepart(dw, (getdate() - 5)) = 6
    ) x where Friday is not null
    
    0 讨论(0)
  • 2021-02-13 01:26

    This is what I got I hope it helps

    DECLARE @UserDate DateTime
    SET @UserDate = '2020-09-03'
    SELECT DATEADD(day, (6 - datepart(weekday, @UserDate)) , @UserDate)
    
    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题