【问题标题】:Raise flag if date exceeds 24 hours excluding weekends如果日期超过 24 小时,周末除外
【发布时间】:2021-02-24 17:18:10
【问题描述】:

我对之前的问题有一个调整后的要求,GMB 能够帮助解决。

以下查询还需要排除周末(周六和周日)

select  s.*,
        case when enddte > dateadd(hh, 24, begindte) 
           then 1 
           else 0 
        end as flag
from shipment s
where ship_id = 14723

基本上,如果在星期五下午 3 点插入带有 dateadd 的条目,则不应在星期六下午 3 点而是在星期一下午 3 点之后的任何时间升起“1”标志

【问题讨论】:

  • 请问您使用的是什么数据库,货件的架构是什么?
  • 我正在使用 MSSQL。对于出货表的字段,enddte 和 begindte 是日期时间字段。

标签: sql sql-server datetime case date-arithmetic


【解决方案1】:

您可以根据begindte的星期几调整偏移量:

set datefirst 1; -- Monday
select s.*,
    case when enddte > dateadd(
        day, 
        case datepart(weekday, begindte)
            when 5 then 3   -- friday:    add 3 days
            when 6 then 2   -- saturday : add 2 day
            else 1          -- else:      add 1 day
        end,
        begindte
    ) then 1 else 0 end as flag
from shipment s
where ship_id = 14723;

【讨论】:

    【解决方案2】:

    您需要将您的查询与:

    DATENAME(weekday,date)
    
    Returns the weekday name for date entered (Sunday,Monday, …,Saturday). 
    

    这是example

    所以基本上是这样的:

    select  s.*,
            case when enddte > dateadd(hh, 24, begindte) AND (DATENAME(weekday, enddte  ) NOT IN ('Saturday','Sunday') OR (DATENAME(weekday, begindte ) = 'Friday' AND enddte > dateadd(hh, 72, begindte)))
               then 1 
               else 0 
            end as flag
    from shipment s
    where ship_id = 14723
    

    【讨论】:

    • 谢谢。我正在使用不支持 DAYOFWEEK 函数的 MSSQL
    • 我发现 GMB 的建议有效。当我刚刚测试你的时,它升起了标志(1),即使它不应该。以下是此示例的日期。 dateadd: 2020-10-16 14:20:22.000 enddte: 2020-10-19 07:04:45.000
    • @VQB begindte 是否在周末(如周六或周日)有记录?
    • 没有。本周的最后一个条目是在星期五输入的。因此,我在 10 月 16 日提供上述日期示例,而 enddte 是在 10 月 19 日星期一。
    • @VQB 好的,你已经在计算 eddate 是在那个场合的星期一。我稍后会编辑我的答案。
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多