Sql 日期之间的一天中的小时数

Sql 日期之间的一天中的小时数,sql,sql-server,Sql,Sql Server,我有一个包含以下列的表格:gkey、ata、atd ata和atd都是日期时间 我想计算出某物每天到达的时间,在它离开之前 示例数据: 预期结果: 您可以使用递归CTE: with cte as ( select gkey, ata, atd, ata as day_start, (case when cast(ata as date) = cast(atd as date) then atd

我有一个包含以下列的表格:gkey、ata、atd

ata和atd都是日期时间

我想计算出某物每天到达的时间,在它离开之前

示例数据:

预期结果:


您可以使用递归CTE:

with cte as (
      select gkey, ata, atd,
             ata as day_start,
             (case when cast(ata as date) = cast(atd as date)
                   then atd
                   else dateadd(day, 1, cast(ata as date))
              end) as day_end
      from t
      union all
      select gkey, day_end, atd,
             day_end as day_start,
             (case when cast(day_end as date) = cast(atd as date)
                   then day_end
                   else dateadd(day, 1, cast(day_end as date))
              end) as day_end
      from cte
      where day_start < cast(atd as date)
     )
select cte.*,
       datediff(minute, day_start, day_end) / 60.0 as num_hours
from cte;

是一个SQL小提琴。

谢谢Gordon,快到了,只需要稍微修改一下num_hours部分:datediffminute,day_start,CASE WHEN CASTatd as Date=CASTata as Date然后atd else day_end end end/60.0 as num_hours
14/06/2017 - 6.5 hours
15/06/2017 - 5.5 hours
18/01/2018 - 4.5 hours
26/02/2018 - 0.05 hours
27/02/2018 - 11.58 hours
with cte as (
      select gkey, ata, atd,
             ata as day_start,
             (case when cast(ata as date) = cast(atd as date)
                   then atd
                   else dateadd(day, 1, cast(ata as date))
              end) as day_end
      from t
      union all
      select gkey, day_end, atd,
             day_end as day_start,
             (case when cast(day_end as date) = cast(atd as date)
                   then day_end
                   else dateadd(day, 1, cast(day_end as date))
              end) as day_end
      from cte
      where day_start < cast(atd as date)
     )
select cte.*,
       datediff(minute, day_start, day_end) / 60.0 as num_hours
from cte;