计算每天的加班时间

时间:2013-07-16 03:39:26

标签: mysql sql

我有一个sql代码,可以获得每个员工的总工作时间和他的时间。我想计算他当天工作的总加班时间。你能帮帮我吗?每天8小时是正常时间。

以下是代码

SELECT
  empno,
  date_created,
  time_in,
  time_out,
  time_format(timediff(time_out, time_in), '%H:%i') AS total_time
FROM
(
  SELECT empno, date_created,
    min(CASE WHEN status = 0 THEN time_created END) time_in,
    max(CASE WHEN status = 1 THEN time_created END) time_out
  FROM biometrics
  WHERE empno = 3
  GROUP BY empno, date_created
) t1;

示例输出

empno| date_created | time_in | time_out
  2      2013-07-15   11:08:07  15:00:00
  3      2013-07-15   11:50:00  NULL
  4      2013-07-15    NULL     16:00:00

我想要的是这样的东西

empno | date_created | time_in | time_out | overtime
 2       2013-07-15    5:00:00  15:00:00      2

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

SELECT empno, date_created, time_in, time_out, 
       CASE WHEN total_hours - 8 > 0 THEN total_hours - 8 ELSE 0 END overtime
  FROM
(
  SELECT empno, date_created, time_in, time_out,
         TIME_TO_SEC(TIMEDIFF(COALESCE(time_out, '17:00:00'),
                              COALESCE(time_in,  '09:00:00'))) / 3600 total_hours
    FROM
  (
    SELECT empno, date_created, 
           MIN(CASE WHEN status = 0 THEN time_created END) time_in,
           MIN(CASE WHEN status = 1 THEN time_created END) time_out
      FROM biometrics
     GROUP BY empno, date_created
  ) a
) b

这是 SQLFiddle 演示

对于time_in的情况,您需要为time_outNULL提供真实的默认值。在极端情况下,NULL是由于员工有一天来回家并且前一天回家,这些默认值可能分别为00:00:0023:59:59,因为您计算加班费日历日。

更新:如果您希望以时间格式显示overtime

SELECT empno, date_created, time_in, time_out, 
       SEC_TO_TIME(
         CASE WHEN total_sec - 28800 > 0 
              THEN total_sec - 28800 
              ELSE 0 END) overtime
  FROM
(
  SELECT empno, date_created, time_in, time_out,
         TIME_TO_SEC(TIMEDIFF(COALESCE(time_out, '17:00:00'),
                              COALESCE(time_in,  '09:00:00'))) total_sec
    FROM
  (
    SELECT empno, date_created, 
           MIN(CASE WHEN status = 0 THEN time_created END) time_in,
           MIN(CASE WHEN status = 1 THEN time_created END) time_out
      FROM biometrics
     GROUP BY empno, date_created
  ) a
) b

这是 SQLFiddle 演示

答案 1 :(得分:0)

SELECT IFNULL(TIMEDIFF('08:00:00',(TIMEDIFF(time_out,time_in))),0) 
AS OVERTIME
FROM biometrics