计算总花费时间不包括暂停

时间:2018-03-07 20:48:37

标签: mysql datediff

我有一种日志表。它会在触发时保存包含任务,状态和时间的记录:

表格tblwork:

+-------------+------------+---------------------+-----+
| task        | status     | stime               | id  |
+-------------+------------+---------------------+-----+
| A           | 1          | 2018-03-07 20:00:00 | 1   |
| A           | 2          | 2018-03-07 20:30:00 | 2   |
| A           | 1          | 2018-03-07 21:00:00 | 3   |
| A           | 3          | 2018-03-07 21:30:00 | 4   |
+-------------+------------+---------------------+-----+

状态1表示开始,2表示暂停,3表示结束。

到目前为止,我尝试这样的事情:

SELECT x1.stime, SUM(TIMEDIFF(x2.stime, x1.stime))
FROM tblwork AS x1 
LEFT JOIN tblwork AS x2
ON x1.id = x2.id + 1
WHERE x1.`status` = 1 OR x1.`status` = 3

但这给了结果-6.000?!?!

我需要计算完成任务所花费的总时间,但要排除暂停。所以最终的结果应该是01:00:00。是否有可能以这种方式做到这一点,还是应该改变表格和逻辑?

更新:解决方案

我想我找到了正确的方法来做我想要的事情:

 SELECT id, stime,
  SUM(TIMESTAMPDIFF(SECOND,
    (SELECT MAX(stime) FROM tblwork WHERE stime < t.stime),
    stime
  )) AS TotalTime
FROM tblwork as t
where (t.status = 1 or t.status = 3)

1 个答案:

答案 0 :(得分:0)

查看您的数据,您应该只加入x1.status = 1并左加入x2.status = 2或3

  SELECT x1.stime, SUM(TIMEDIFF(x2.stime, x1.stime))
  FROM tblwork AS x1 
  LEFT JOIN tblwork AS x2 ON x1.id = x2.id + 1 
        AND (x2.status = '2' OR x2.status = '3')
  WHERE x1.`status` = 1