代码之家  ›  专栏  ›  技术社区  ›  Mutai

范围内的日期[关闭]

  •  0
  • Mutai  · 技术社区  · 6 年前

    我有一个场景,在这个场景中,我们有各种各样的订单,在开始和结束的时间内完成。我尝试只获取特定时间范围内的记录,并以秒为单位计算持续时间。为了论证,我们假设24小时。我需要使用下面的命令,看看哪些命令调用范围内,并只计算每个命令之间的持续时间在24小时的时间框架/日期范围内。超出每个订单时间范围的任何内容都不会影响每个订单的持续时间。我有和下面非常相似的数据。

    Order #         Start                           End
    Order 1         2018-09-20 11:00.00.000         2018-09-21 09:00.00.000
    Order 2         2018-09-20 10:30.00.000         2018-09-21 08:00.00.000
    Order 3         2018-09-20 10:21.00.000         2018-09-20 18:00.00.000
    Order 4         2018-09-20 11:50.00.000         2018-09-21 10:00.00.000
    Order 5         2018-09-20 19:00.00.000         2018-09-21 02:00.00.000
    

    2018-09-20 11:00.00.000 to 2018-09-21 11:00.00.000

    1 回复  |  直到 6 年前
        1
  •  4
  •   Adrian Maxwell    6 年前

    下图试图解释按日期/时间范围选择数据的逻辑:

    Period Start "Ps"
    Period End "Pe"
    
        Ps       Pe
    s-E |        |        ignore, starts & ends before the period (E not > Ps)
    
     s--|--------|-E      spans the period
      s-|---E    |        start before, but ends in, the period
        s----E   |        starts at beginning of the period, finishes before the period ends
        | s---E  |        starts and finished within the period
        |   s----E        starts within the period, finishes on last day of the period
        |     s--|-E      starts within the period but finishes after the period
    
        |        | s-E    ignore, starts & ends after the period (s not < Pe)
    
         s < Pe
       + E >= Ps
    

    DECLARE @Ps AS datetime = '2018-09-20 11:00.00.000'
    DECLARE @Pe AS datetime = DATEADD(HOUR, 24, @Ps)
    
    SELECT
        t.*
    FROM yourtable AS t
    WHERE t.[start] < @Pe
    AND t.[end] >= @Ps