如果 SQL Server 中当天是周末(周六至周日),则返回周五

Hal*_*wen 1 sql t-sql database sql-server

我将历史数据存储为 SQL Server 中的日期类型 (2019-10-10)。我想检查并返回星期五是否是星期六或星期日。

周末没有数据。这就是为什么我想在周末获取周五的数据。

HAB*_*ABO 5

( @@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.

You can use the following code to push weekend dates back to the prior Friday:

-- Get the current date (without time).
declare @Today as Date = GetDate();
-- Move Saturday or Sunday dates back to the prior Friday.
select @Today as Today,
  case ( @@DateFirst + DatePart( weekday, @Today ) - 1 ) % 7 + 1
    when 1 then DateAdd( day, -2, @Today ) -- Sunday.
    when 7 then DateAdd( day, -1, @Today ) -- Saturday.
    else @Today end as ReportDate;
Run Code Online (Sandbox Code Playgroud)