首页 > 解决方案 > 使用 case 语句通过 dateadd 排除周末

问题描述

我必须在某个日期(示例日期)之前至少 3 天设置提醒日期。如果该日期设置为周二或周三,则提醒日期将设置为周六和周日发送。我考虑过提前 4 天将提醒日期设置为星期二,提前 5 天设置为星期三。这样我所有的提醒都会在一周内发送出去。我考虑过使用dateaddwith case 语句,但不确定如何在我的datedd函数中加入某些工作日。

select dateadd (day,-3,convert(char(10),sample_date,101)) as Reminder_Sent 

-- Ideally, my query should look like something like the below: 

select 

case when dateadd (monday,-3,convert(char(10),sample_date,101)) as Monday_Reminder_Sent
when dateadd (Tuesday,-4,convert(char(10),sample_date,101)) as Tuesday_Reminder_Sent
When dateadd (Wednesday,-5,convert(char(10),sample_date,101)) as Wednesday_Reminder_Sent
when dateadd (Thursday,-3,convert(char(10),sample_date,101)) as Thursday_Reminder_Sent
Else as Reminder_Sent
End

标签: sqlsql-servertsql

解决方案


您可以使用 datename 进行比较。查看您的逻辑,您将仅对星期二和星期三进行不同的计算,在这种情况下,它应该返回星期五而不是周末。其他所有日子,您需要返回 3 天。

declare  @sample_date     datetime 
set @sample_date = getdate()

select @sample_date as date , case   DATENAME ( weekday,@sample_date ) 
                when 'Tuesday' then dateadd (day,-4,convert(char(10),@sample_date ,101))
                when 'Wednesday' then dateadd (day,-5,convert(char(10),@sample_date ,101))
            else dateadd (day,-3,convert(char(10),@sample_date,101)) 
            end as Reminder_Sent 

您也可以使用 DATEPART。但是您必须先设置 DATEFIRST。


推荐阅读