Sum timelog for each day in sql

Peter Nordberg
Peter Nordberg used Ask the Experts™

I have a table with data looking like this:
Sql result
The purpose of the table is to register a log for Employees so you can see the times they've worked.
As you can see each day has a rowID and also a TimeClockCatID. The rowID is the id for the specific day they are registering for and the TimeClockCatID is showing if they checked in (1) or checked out (2) from the system.

Is it possible for me to count and sum how much time an employee has worked a day by comparing the TimeClockCatID = 1 with TimeClockCatID  = 2 for each rowID?

Thanks for help!

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
SQL Server DBA & Architect, EE Solution Guide
Awarded 2009
Distinguished Expert 2018
This should help match your requirements.. Hope the columns I've displayed would be sufficient..please feel free to make any changes as required..
create table ur_table( EmployeeId int, cTimestamp datetime, TimeClockTypeId int, TImeclockCatId int, rowId int)
insert into ur_table values
(120, '2018-07-02 09:00', 3, 1, 129)
,(120, '2018-07-02 10:00', 3, 2, 129)
,(120, '2018-07-02 13:00', 3, 1, 129)
,(120, '2018-07-02 16:00', 3, 2, 129)
,(120, '2018-07-03 08:00', 3, 1, 130)
,(120, '2018-07-03 12:00', 3, 2, 130)
,(120, '2018-07-04 08:15', 3, 1, 131)
,(120, '2018-07-04 11:50', 3, 2, 131)

; with cte as (
select  cTimestamp, EmployeeId, rowId, TimeClockTypeId, TimeclockCatId
, row_number() over (partition by employeeId, TimeclockTypeId, rowid order by ctimestamp) rnum
from ur_table)
select t1.EmployeeId, t1.rowid, cast(t1.cTimestamp as date) cdate, SUM(datediff(mi, t1.ctimestamp, t2.ctimestamp) ) Minutes
from cte t1
left join cte t2 on t1.EmployeeId  = t2.EmployeeId and t1.rowId = t2.rowId and t1.rnum = t2.rnum -1
WHERE t1.TImeclockCatId = 1 and t2.TImeclockCatId = 2
GROUP BY t1.EmployeeId, t1.rowid,cast(t1.cTimestamp as date)

Open in new window

Peter NordbergIT Manager


Works like a charm:) Thanks!
Raja Jegan RSQL Server DBA & Architect, EE Solution Guide
Awarded 2009
Distinguished Expert 2018

Welcome, glad to help..

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial