mysql - SQL SERVER (TSQL) SUM of inverse DateDiff (SQL or Stored Procedure) -


i have tricky sql create, having table:

+-----------------------+ | employee login logout | +-----------------------+ | 1        08:30 08:50  | | 1        09:00 10:00  | | 1        10:20 11:00  | +-----------------------+ 

i need sql sum break times:

08:50 -> 09:00 = 10 minutes + 10:00 -> 10:20 = 20 minutes = 30 minutes in total 

so need somehow go on each record , using datediff method sum duration of breaks between records.

is there easy way using sql or stored procedure?

as commented @thebjorn, first difference between first login , last logout (work shift) , subtract sum of difference of each login-logout pair (actual time you're working). result total time you're not working or break time.

;with sampledata(employee, login, logout) as(     select 1, cast('08:30' time), cast('08:50' time) union     select 1, cast('09:00' time), cast('10:00' time) union     select 1, cast('10:20' time), cast('11:00' time) ) select      employee,     totalbreaktime = datediff(minute, min(login), max(logout)) -  sum(datediff(minute, login, logout)) sampledata group employee 

using lag function

;with sampledata(employee, login, logout) as(     select 1, cast('08:30' time), cast('08:50' time) union     select 1, cast('09:00' time), cast('10:00' time) union     select 1, cast('10:20' time), cast('11:00' time) union     select 2, cast('10:00' time), cast('10:30' time) union     select 2, cast('10:45' time), cast('11:30' time) ) ,ctebreaktime as(     select *,         breaktime = datediff(minute, lag(logout) over(partition employee order login), login)     sampledata ) select     employee,     totalbreaktime = sum(breaktime)  ctebreaktime group employee 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -