我正在研究一种复杂的 mysql 查询来计算员工在某一天的总工作时间。它适用于某些员工,但不适用于其他员工。我已经创建了一个 SQL Fiddle,所以你可以很容易地看到我在说什么。 http://sqlfiddle.com/#!2/6439f/1/0
数据:
CREATE TABLE punches
(
PunchID int auto_increment primary key,
EmpID varchar(6),
Name varchar(20),
PunchDateTime DateTime,
PunchEvent varchar(20),
`In-Out` int
);
INSERT INTO punches
(EmpID, Name, PunchDateTime, PunchEvent, `In-Out`)
VALUES
('0538', 'ROXANNE NIESEN', '2013-06-17 07:27:48', 'clockin', 1),
('0538', 'ROXANNE NIESEN', '2013-06-17 16:57:30', 'clockout', 0),
('1102', 'JEFFERY POTTER', '2013-06-17 07:29:44', 'clockin', 1),
('1102', 'JEFFERY POTTER', '2013-06-17 16:29:57', 'clockout', 0),
('1588', 'BRUCE COLEMAN', '2013-06-17 06:20:48', 'clockin', 1),
('1588', 'BRUCE COLEMAN', '2013-06-17 12:15:18', 'breakout', 0),
('1588', 'BRUCE COLEMAN', '2013-06-17 12:43:58', 'breakin', 1),
('1588', 'BRUCE COLEMAN', '2013-06-17 17:00:37', 'clockout', 0);
询问:
SELECT Name, DATE_FORMAT(p.PunchDateTime, '%m-%d-%Y') AS 'Punch Date',
TIME(SUM(p.PunchDateTime * (1 - 2 * `p`.`In-Out`))) AS 'Hours Worked Time',
SUM(p.PunchDateTime * (1 - 2 * `p`.`In-Out`)) AS 'Hours Worked',
SUM(UNIX_TIMESTAMP(p.PunchDateTime*(1-2*`p`.`In-Out`)))/3600 AS 'Hours Worked Decimal'
FROM punches p
WHERE DATE(p.PunchDateTime) = '2013-06-17'
GROUP BY DATE(p.PunchDateTime), EmpID
结果:
| NAME | PUNCH DATE | HOURS WORKED TIME | HOURS WORKED | HOURS WORKED DECIMAL |
------------------------------------------------------------------------------------------------------
| ROXANNE NIESEN | 06-17-2013 | (null) | 92982 | 380968.9583 |
| JEFFERY POTTER | 06-17-2013 | January, 01 1970 09:00:13+0000 | 90013 | 380968.4992 |
| BRUCE COLEMAN | 06-17-2013 | January, 01 1970 10:51:49+0000 | 105149 | 761933.2653 |
Roxanne 的第一个结果应该是返回时间,它返回 NULL。Jeffery 的第二个工作正常。布鲁斯的第三个是返回时间,但我计算的时间是错误的。有谁知道这里发生了什么?谢谢迈克