How do I calculate the total amount number of hours spend inside in SQL? For instance, for this employee, the total amount of hours spent inside would 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
In SQL Server 2008, this is painful. Assuming that the Entry/Exit values are connected and the time is really a valid date time, you can do:
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;