如何计算一天中的总记录时间?

时间:2019-04-11 00:29:48

标签: sql sql-server-2008 ssrs-2008

如何计算在SQL中花费的总时数?例如,对于这名员工,内部工作的总时间为12-2 = 10。

EmpID   Enter/Exit  Time 
 2999   Entry   06:00AM 
 2999   Exit    12:00PM
 2999   Entry   01:00PM 
 2999   Exit    03:00PM 
 2999   Entry   04:00PM
 2999   Exit    06:00PM

1 个答案:

答案 0 :(得分:3)

在SQL Server 2008中,这很痛苦。假设已连接“进入/退出”值并且该时间实际上是一个有效的日期时间,则可以执行以下操作:

select empid,
       sum(datediff(hour, t.time, t2.time)) as sum_hours
from t cross apply
     (select top (1) t2.*
      from t t2
      where t2.empid = t.empid and
            t2.enter_exit = 'exit' and
            t2.time > t.time
     ) as next_time
where t.enter_exit = 'enter'
group by empid;