获取基于星期几的总工作时间

时间:2018-07-24 07:57:06

标签: mysql

我要检查员工的每日工作时间是否少于分配的总工作时间。

例如,将1号员工分配给工作:

Day | Total working hours
mon | 10
tue | 10
wed | 10
thu | 10
fri | 10
sat | 0
sun | 0

我的#1号员工的总工作时间如下:

Start               | End                         | Total Hours Worked
2018-07-02 00:28:29 | 2018-07-02 04:12:17         | 3.72 
2018-07-05 00:26:20 | 2018-07-05 05:03:23         | 4.62 
2018-07-12 00:27:35 | 2018-07-12 10:21:08         | 9.88

我面临的问题是要知道在星期几中根据日期检查总工作时间。例如2018年7月2日是星期一,因此员工应该工作的总工作时间为10个小时,但员工的总工作时间仅为3.72。因此,对于2018-07-02,员工尚未完成分配的总工作时间。

预期的查询结果应返回:

Short Working Hour Date 
2018-07-02
2018-07-05
2018-07-12

感谢你们的任何帮助。谢谢

2 个答案:

答案 0 :(得分:0)

我找到了一种参考手册的方法。但这看起来很乱。

SELECT
    start,
    end,
    total_hours_worked
FROM mytable
GROUP BY DATE(start), DATE(end)
having CASE 
    WHEN DAYOFWEEK(MIN(start))=1 and total_hours_worked < 0   THEN 1 
    WHEN DAYOFWEEK(MIN(start))=2 and total_hours_worked < 10  THEN 1 
    WHEN DAYOFWEEK(MIN(start))=3 and total_hours_worked < 10  THEN 1 
    WHEN DAYOFWEEK(MIN(start))=4 and total_hours_worked < 10  THEN 1 
    WHEN DAYOFWEEK(MIN(start))=5 and total_hours_worked < 10  THEN 1 
    WHEN DAYOFWEEK(MIN(start))=6 and total_hours_worked < 10  THEN 1 
    WHEN DAYOFWEEK(MIN(start))=7 and total_hours_worked < 0   THEN 1 
    ELSE 0 
END;

答案 1 :(得分:0)

我不完全了解您的要求,所以这是一个不完整的解决方案...

DROP TABLE employee_assignments;

CREATE TABLE employee_assignments
(day CHAR(3) NOT NULL PRIMARY KEY
,total_working_hours INT NOT NULL DEFAULT 0
);

INSERT INTO employee_assignments VALUES
('mon',10),
('tue',10),
('wed',10),
('thu',10),
('fri',10),
('sat',0),
('sun',0);

DROP TABLE timesheet;

CREATE TABLE timesheet
(start DATETIME NOT NULL PRIMARY KEY
,end  DATETIME NOT NULL 
);

INSERT INTO timesheet VALUES
('2018-07-02 00:28:29','2018-07-02 04:12:17'),
('2018-07-05 00:26:20','2018-07-05 05:03:23'),
('2018-07-12 00:27:35','2018-07-12 10:21:08');

SELECT t.*
     , (TIME_TO_SEC(t.end)-TIME_TO_SEC(t.start))/3600 n 
     , a.*
  FROM timesheet t
  JOIN employee_assignments a
    ON a.day = DATE_FORMAT(t.start,'%a');

+---------------------+---------------------+--------+-----+---------------------+
| start               | end                 | n      | day | total_working_hours |
+---------------------+---------------------+--------+-----+---------------------+
| 2018-07-02 00:28:29 | 2018-07-02 04:12:17 | 3.7300 | mon |                  10 |
| 2018-07-05 00:26:20 | 2018-07-05 05:03:23 | 4.6175 | thu |                  10 |
| 2018-07-12 00:27:35 | 2018-07-12 10:21:08 | 9.8925 | thu |                  10 |
+---------------------+---------------------+--------+-----+---------------------+