计算员工的缺勤时间



我有表格来存储员工的出勤数据,如下所示:

EmployeeID|   Date   |EnterTime|ExitTime|
    1     |2017-01-01|07:11:00 |15:02:00|
    2     |2017-01-01|07:30:00 |12:00:00|
    2     |2017-01-02|07:00:00 |15:00:00|
    1     |2017-01-02|07:30:00 |10:00:00|
    1     |2017-01-02|11:20:00 |15:00:00|
    1     |2017-01-03|09:30:00 |10:00:00|
    1     |2017-01-03|11:20:00 |15:00:00|

实际上我的工作时间是从07:00:00到15:00:00。

我想总结一下每个员工的缺勤时间,例如: 在 2017-01-01 对于员工 ID 2,是 03:00:00 小时作为缺勤在日期 2017-01-02 中,员工 ID 1 为 01:00:00 小时。在日期 2017-01-03 中,员工 ID 1 是 02:30:00员工 ID 2 缺勤是 08:00:00 小时,因为我的表中没有日志。最后需要以下报告:

EmployeeID|TotalWorkingHour       |TotalAbsenceHour|
    1     |sum(EnterTime-ExitTime)|05:09:00        |
    2     |sum(EnterTime-ExitTime)|11:30:00        |

我通过以下选择获得总工作秒数,但不知道如何计算缺勤秒数:

select EmployeeID,
sum(datediff(second,Convert(DATETIME, EnterTime, 114), Convert(DATETIME, ExitTime, 114)) ) as TotalWorkingSeconds 
from Attendance
where Attendance.Date between @FromDate and @ToDate 
and (EnterTime is not null) 
and (ExitTime is not null)
group by EmployeeID

这可能不是最终和完美的解决方案,但它可以:

DECLARE @StartDate DATE, @EndDate DATE
SET @StartDate = '2016-12-31'
SET @EndDate =  '2017-01-05' -- GETDATE()
SELECT alldate_and_employee.EmployeeID
      ,alldate_and_employee.Date
      ,COALESCE(employee_workingdays.WorkingMinutes,0) as TimeWorked
      ,(alldate_and_employee.PlannedWorkingTime - COALESCE(employee_workingdays.WorkingMinutes,0)) as  WorkedTooLessMinutes
  FROM
  (
     -- returns a table with a combination of all Employees and all Dates
     SELECT DISTINCT EmployeeID, datelist.Date, 480 as PlannedWorkingTime
       FROM mytable
      CROSS JOIN
      (
        -- selects all dates between @StartDate and @Enddate
        SELECT DATEADD(DAY,number+1,@StartDate) [Date]
        FROM master..spt_values
        WHERE type = 'P'
        AND DATEADD(DAY,number+1,@StartDate) < @EndDate
      ) datelist
  ) alldate_and_employee
  LEFT OUTER JOIN
  (
      -- groups the working time of each employee for a working day
      SELECT EmployeeID
           ,Date 
           ,SUM(DATEDIFF(minute, EnterTime, ExitTime)) as WorkingMinutes
        FROM mytable
    GROUP BY EmployeeID
            ,Date 
  ) employee_workingdays
  ON employee_workingdays.Date       = alldate_and_employee.Date
 AND employee_workingdays.EmployeeID = alldate_and_employee.EmployeeID
ORDER BY alldate_and_employee.Date, alldate_and_employee.EmployeeID

相关内容

  • 没有找到相关文章

最新更新