在SQL Server中使用DATEDIFF计算工作时间

时间:2018-06-21 06:32:16

标签: sql-server datetime

我目前很难计算员工的总工作时间,尤其是夜班人员。这是我的代码:

DECLARE @StartTime time
DECLARE @EndTime time

SELECT @StartTime = CAST('Jun 04 2018 8:00PM' as time)
SELECT @EndTime = CAST('Jun 04 2018 5:00AM' as time)

SELECT
SUM((DATEDIFF(MINUTE, @StartTime, @EndTime) - isnull(datediff(minute, break_start, break_end), 0))/ 60.0) 
FROM pmis.dbo.employee as a
LEFT JOIN pmis.dbo.time_reference as b ON b.code = ISNULL(a.TimeReference, 'TIME14')
    cross apply
    (
        select  break_start = case  when b.break_from between @StartTime and @EndTime
                 then b.break_from
                 when @StartTime between b.break_from and b.break_to
                 then @StartTime
                 else NULL
                end,
                break_end  = case   when b.break_to between @StartTime and @EndTime
                 then b.break_to
                 when @EndTime between b.break_from and b.break_to
                 then @EndTime
                end
        ) as d
WHERE
a.Shift = 0 and a.eid = 7078

我得到的是给定时间是这样

@StartTime = 8:00 AM
@EndTime = 5:00 PM

结果完全是我想要的8.00小时,但如果是这样

@StartTime = 8:00 PM
@EndTime = 5:00 AM

当我收到-15.00时,该如何解决?谢谢

2 个答案:

答案 0 :(得分:1)

尝试在结束时间早于开始时间时将1天(1440分钟)添加到计算中。但是,这不会处理墓地转移中的中断。但是您以前的代码有相同的问题

MessageBox.Show(await GetMessages())

答案 1 :(得分:0)

另一种解决方法是使用datetime数据类型而不是时间,那么您需要更改这些行

DECLARE @StartTime datetime
DECLARE @EndTime datetime

SELECT @StartTime = CAST('Jun 04 2018 8:00PM' as datetime)
SELECT @EndTime = CAST('Jun 04 2018 5:00AM' as datetime)