sql server - SQL : Calculating employee utilization hours for each day -
sql : have table employee working hours in starttime , endtime column. want calculate working hours each employee each day employee starts he's shift on 1 day , ends on next day.
|employee |starttime |endtime | |a | 01/01/2001 23:00 |02/01/2001 10:00| |b | 01/01/2001 21:00 |01/01/2001 22:00| output: |employee |date |hoursworked |a | 01/01/2001 | 1 | |a | 02/01/2001 | 10 | |b | 01/01/2001 | 1 |
here approach using recursive ctes:
declare @t table( employee nvarchar(10) ,starttime datetime ,endtime datetime ) insert @t values ('a', '2001-01-01 23:00:00', '2001-01-03 10:00:00') ,('a', '2001-01-05 21:00:00', '2001-01-06 22:00:00') ,('a', '2001-01-07 21:00:00', '2001-01-08 22:00:00') ,('b', '2001-01-01 21:00:00', '2001-01-01 22:00:00') ,('b', '2001-01-02 21:00:00', '2001-01-03 02:00:00') ,('c', '2001-01-03 02:00:00', '2001-01-04 00:00:00'); cte as( select 1 lvl, employee, convert(date, starttime) starttime_date, starttime, endtime @t t union select lvl + 1 lvl, c.employee, dateadd(d, 1, c.starttime_date) starttime_date, c.starttime, c.endtime cte c dateadd(d, 1, c.starttime_date) < c.endtime ), ctecalc as( select * ,convert(date, starttime) startdate ,case when lvl > 1 convert(datetime,convert(date, dateadd(d, datediff(d, starttime, starttime_date), starttime))) else dateadd(d, datediff(d, starttime, starttime_date), starttime) end starttimenew ,isnull(convert(datetime, lead(starttime_date) on (partition employee, convert(date, starttime) order starttime_date)), endtime) endtimenew cte ) select employee, starttime_date startdate, datediff(minute, starttimenew, endtimenew)/60.0 workhours ctecalc order employee, starttime_date option (maxrecursion 0)
Comments
Post a Comment