间隔时间

时间:2019-03-05 03:09:16

标签: sql sql-server tsql

我有一个像这样的时间表清单

Start Time 2016-6-20 7:30AM       End Time 2016-6-20 8:00AM

我想创建一个查询来计算间隔之间的持续时间,它可以工作30分钟,但是我不知道如何在2:45或2:15结束时创建一个查询。如果我与diff约会,我会给我30分钟的持续时间,但是对于2:15或2:45,它不会给我

我想要看起来像

7:30, Start time7:30, End Time 8:00AM, durwtion 30 minutes 
8:00, Start time 8:00, End time 8:15, duration  15 minutes 

1 个答案:

答案 0 :(得分:0)

您的意思是这样的吗?修复hr:min是一项任务,但几分钟很容易。

declare @starttime datetime = '2016-6-20 7:30AM'
declare @endtime datetime = '2016-6-20 8:00AM'
select rtrim(datediff(minute,@starttime, @endtime)) + ' min'

编辑,尝试此查询

;with duration_dates as 
( 
    SELECT top (100)
        dateadd(minute,(datediff(minute,0,Start_Time_UTC)/ 15)*15,0) Start_Time_UTC
        ,dateadd(minute,(datediff(minute,0,dateadd(minute,15,End_time_UTC))/15)*15,0) End_time_UTC 
        --,<your id column here>
    FROM EmployeeSchedules
)
SELECT
     TimeInterval 
    ,Start_Time_UTC 
    ,End_time_UTC
    ,datediff(minute, Start_Time_UTC,End_time_UTC) duration 
FROM Times 
LEFT JOIN duration_dates ON CAST(Start_Time_UTC AS Time) = TimeInterval