计算员工在一天的缺勤时间

时间:2017-06-21 07:17:03

标签: c# sql visual-studio time time-and-attendance

我有用于存储员工出勤数据的表格如下:

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作为缺席 员工ID 1的日期2017-01-02为01:00:00。 在2017-01-03日期,员工ID为02:30:00 因为我的表中没有记录,员工ID缺席时间是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

1 个答案:

答案 0 :(得分:0)

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

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