SQL WHERE 取决于星期几

SQL WHERE depending on day of week

我需要检查不同日期的记录,具体取决于当前是星期几。

在周五,我需要它查看整个下周,直到下周日。在任何其他日子,它应该检查当前周,直到下周日。

我目前有以下内容,但由于语法错误无法使用。是否可以在 WHERE 子句中执行 CASE WHEN

WHERE
    T0.[Status] IN ('R','P') 
    AND
        CASE 
           WHEN DATEPART(weekday,GETDATE()) = '5' 
              THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())
           WHEN DATEPART(weekday, GETDATE()) != '5' 
              THEN T0.[DueDate] >= GETDATE() AND <= DATEADD(DAY ,8- DATEPART(weekday, GETDATE()), GETDATE())
        END

使用一系列逻辑 orand 运算符创建此逻辑要容易得多:

WHERE
T0.[Status] IN ('R','P') AND
((DATEPART(weekday,GETDATE()) = '5' AND 
  T0.[DueDate] >= GETDATE() AND 
  T0.[DueDate] <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())) OR
 (DATEPART(weekday,GETDATE()) != '5' AND 
  T0.[DueDate] >= GETDATE() AND 
  T0.[DueDate] <= DATEADD(DAY ,8- DATEPART(weekday,GETDATE()),GETDATE())
)

您的语法错误,您在 THEN 子句中使用了条件评估而不是 assignemnet

  WHEN DATEPART(weekday,GETDATE()) = '5' THEN  Your_column1  ELSE your_column2 END
  ......

或内壳

  CASE
    WHEN DATEPART(weekday,GETDATE()) = '5' THEN 
            CASE  WHEN T0.[DueDate] >= GETDATE() 
                    AND <= DATEADD(day, 15 - DATEPART(weekday, GetDate()), GetDate())  
                    THEN Your_column1  ELSE your_column2 
            END 
 END
   ......