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

How to calculate the total logged time in a day?

如何计算在 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

在 SQL Server 2008 中,这很痛苦。假设 Entry/Exit 值已连接并且时间确实是有效的日期时间,您可以这样做:

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;