我试图总结所有时差差异值并以HH:mm:ss格式显示,但结果应该少于。
以下是我的DDL和我到目前为止的尝试:
CREATE TABLE tblproduction
(
OperaterID int,
OperationID varchar(20),
StartDateTime datetime,
EndDateTime datetime
);
INSERT INTO `tblproduction` VALUES
(227, 'OPEE21', '2014-12-01 05:51:34', '2014-12-01 06:48:30'),
(227, 'OPEE21', '2014-12-01 06:54:37', '2014-12-01 10:14:30'),
(227, 'OPEE21', '2014-12-01 10:23:03', '2014-12-01 13:41:31'),
(227, 'OPEE21', '2014-12-02 05:54:09', '2014-12-02 07:50:53'),
(227, 'OPEE21', '2014-12-02 07:55:03', '2014-12-02 13:37:56'),
(227, 'OPEE21', '2014-12-09 14:06:57', '2014-12-09 17:20:09'),
(227, 'OPEE21', '2014-12-09 17:22:07', '2014-12-09 21:51:24'),
(227, 'OPEE21', '2014-12-11 14:06:12', '2014-12-11 18:36:47'),
(227, 'OPEE21', '2014-12-12 14:07:09', '2014-12-12 14:58:42'),
(227, 'OPEE21', '2014-12-12 15:05:23', '2014-12-12 15:49:37'),
(227, 'OPEE21', '2014-12-12 15:55:12', '2014-12-12 21:55:24'),
(227, 'OPEE21', '2014-12-15 05:54:42', '2014-12-15 12:32:58'),
(227, 'OPEE21', '2014-12-15 12:38:48', '2014-12-15 13:40:08'),
(227, 'OPEE21', '2014-12-18 10:47:07', '2014-12-18 13:36:55'),
(227, 'OPEE21', '2014-12-19 06:16:58', '2014-12-19 13:37:29'),
(227, 'OPEE21', '2014-12-22 14:09:29', '2014-12-22 21:53:45'),
(227, 'OPEE21', '2014-12-23 14:26:54', '2014-12-23 17:12:13'),
(227, 'OPEE21', '2014-12-23 17:14:11', '2014-12-23 18:00:40'),
(227, 'OPEE21', '2014-12-23 18:03:51', '2014-12-23 21:07:57'),
(227, 'OPEE21', '2014-12-23 21:08:56', '2014-12-23 21:46:58');
SELECT p.OperaterID
, p.OperationID
, p.StartDateTime
, p.EndDateTime
, TIME_FORMAT(SUM(TIMEDIFF(p.EndDateTime, p.StartDateTime)), '%H:%i:%s') TotalTime
FROM tblproduction p
WHERE p.StartDateTime >= '2014-12-01 00:00:00'
AND p.StartDateTime <= '2014-12-31 23:59:59'
AND p.OperaterID = 227
AND p.OperationID = 'OPEE21'
GROUP
BY p.OperationID;
+------------+-------------+---------------------+---------------------+-----------+
| OperaterID | OperationID | StartDateTime | EndDateTime | TotalTime |
+------------+-------------+---------------------+---------------------+-----------+
| 227 | OPEE21 | 2014-12-01 05:51:34 | 2014-12-01 06:48:30 | 63:48:44 |
+------------+-------------+---------------------+---------------------+-----------+
......还有一个相同的小提琴 SQL Fiddle
结果应为67:52:04,但查询返回63:48:44。我现在不会失去4个小时。
答案 0 :(得分:2)
在TIMEDIFF结果上应用SUM。您应首先将TIMEDIFF转换为秒,而不是SUM,然后转换回来。
SELECT OperaterID, OperationID,
StartDateTime, EndDateTime,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(tblproduction.EndDateTime, tblproduction.StartDateTime)))) AS TotalTime
FROM tblproduction
WHERE StartDateTime >= '2014-12-01 00:00:00' AND StartDateTime <= '2014-12-31 23:59:59' AND OperaterID = 227 AND OperationID = 'OPEE21'
GROUP BY OperationID;
答案 1 :(得分:1)
这是一种方式......
SELECT operaterid
, operationid
, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(EndDateTime,StartDateTime)))) total
FROM tblproduction
GROUP
BY operaterid
, operationid;