【问题标题】:Raise flag if date exceeds 1 day / 24 hours如果日期超过 1 天/24 小时,则升旗
【发布时间】:2021-02-19 12:35:47
【问题描述】:

我正在尝试创建一个列,当持续时间为自初始日期之日起的一天(24 小时或更长时间)时,该列会引发标志。

select 
    case when (enddte - begindte) > '23:59:59.000'  
        then '1' 
        else '0' 
    end as flag 
from shipment 
where ship_id = '14723'

注意事项: enddte 和 begindte 的日期格式如下,例如:2017-09-06 20:22:36.000

我需要进一步分解上面计算天 - 天和小时 - 小时的案例陈述吗?

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:mysql、oracle、postgresql...?另外,begindteenddte 列的数据类型是什么?
  • @GMB:看起来 OP 正在使用 MSSQL。我相应地更新了标签。另外:我不确定 OP 是如何调用此查询的,但我不确定“选择案例何时”是最好的方法......
  • @GMB,是的,我正在使用 MSSQL。数据类型是日期时间。我在想查询应该看起来像这样,但还没有让它工作。选择 case when (datediff(hour,enddte, begindte)/24.0) > 1 then '1' else '0' end as flag from shipping where ship_id = '14723'

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


【解决方案1】:

我相信,我想通了。

select 
    case 
        when (datediff(hour,enddte, begindte)/24.0) > 1 
            then '1' 
            else '0' 
        end as flag 
from shipment 
where ship_id = '1326747-2'

【讨论】:

    【解决方案2】:

    datediff() 不是完成这项任务的好工具。每次越过边界时,它都会增加 1,这会产生某种违反直觉的结果。通常情况下,今天 13:59 和今天 14:01 之间的小时差是 1。

    您可以使用简单的日期算术,如下所示:

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

    当然,这假定这两列是合法的类似日期的数据类型,例如datetimedatetime2

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多