sql - 使用 case 语句通过 dateadd 排除周末
问题描述
我必须在某个日期(示例日期)之前至少 3 天设置提醒日期。如果该日期设置为周二或周三,则提醒日期将设置为周六和周日发送。我考虑过提前 4 天将提醒日期设置为星期二,提前 5 天设置为星期三。这样我所有的提醒都会在一周内发送出去。我考虑过使用dateadd
with 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
解决方案
您可以使用 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。
推荐阅读
- python - 如何使用解密密钥加密和解密熊猫数据帧?
- r - (在 R 中)将元数据从向量添加到数据帧的一组列?
- c++ - C ++将未知数量的整数读取到cin并输出总和
- ms-access - 访问查询:将Like "*2018*" 中的2018 替换为当前年份
- c# - 如何使 PicBox 形成?
- reactjs - Reactjs - 单个 React 应用程序中的多个标题
- sql-server - SQL Server - 隐式事务连接字符串
- java - 复杂的条件和不可达的语句
- node.js - npm准备脚本不在节点模块中构建文件夹
- javascript - 随机生成具有随机尺寸且无冲突的矩形