【发布时间】:2018-09-14 15:00:52
【问题描述】:
我有一个表格,其中包含触发时的任务、状态和时间记录:
表格工作:
+-------------+------------+---------------------+-----+
| 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 |
| B | 1 | 2018-03-07 22:30:00 | 5 |
| B | 3 | 2018-03-07 23:30:00 | 6 |
+-------------+------------+---------------------+-----+
状态 1 表示开始,2 - 暂停,3 - 结束
然后我需要计算每个任务花费了多少时间,不包括暂停(状态 = 2)。我就是这样做的:
SELECT t1.id, t1.task,
SUM(timestampdiff(second,IFNULL(
(SELECT MAX(t2.stime) FROM tblwork t2 WHERE t2.task='B' AND t2.stime< t1.stime) ,t1.stime),t1.stime)) myTimeDiffSeconds
FROM tblwork t1
WHERE t1.task='B' and (t1.status = 1 or t1.status = 3);
现在我想获取所有任务的表格
SELECT t1.id, t1.task,
SUM(timestampdiff(second,IFNULL(
(SELECT MAX(t2.stime) FROM tblwork t2 WHERE t2.stime< t1.stime) ,t1.stime),t1.stime)) myTimeDiffSeconds
FROM tblwork t1
WHERE (t1.status = 1 or t1.status = 3) GROUP BY t1.taks
我得到这个结果:
+-------------+------------+---------------------+
| task | id | mytimedifference |
+-------------+------------+---------------------+
| A | 1 | 3600 |
| B | 3 | 2421217 |
+-------------+------------+---------------------+
A 计算正确 B 错误,应该是 3600 秒,但我不明白为什么。
【问题讨论】:
-
"A 计算正确 B 错误" 任务
A的 mytimedifference 不应该是 3600 秒(1 小时)而不是 7200 秒(2 小时)吗? ... 开始2018-03-07 20:00:00结束2018-03-07 21:30:00减去 30 分钟的休息时间。 -
不太确定 id 的相关性应该是什么; B 从不与源数据中的 id = 3 相关联。
-
是的,你是对的。抱歉,打错字了。
-
我假设列 id 是带有 auto_increment 选项的主键?在结束前还有不止一个休息时间吗?
-
and 之前可以有更多的中断。见这个例子sqlfiddle.com/#!9/050a41/1
标签: mysql datetime time datediff timestampdiff