我有两个字段:
我的查询是:
SELECT TIMEDIFF(Final, Initial)
AS 'Worked Hours'
FROM `db_foo`
WHERE matriculation='X' AND date='2017-yy-yy'
结果将类似于
Worked Hours
03:34:00
02:34:00
01:00:00
[...]
是否可以对这些多个时间戳进行进一步求和,以便获得总工作时数?
示例数据集(以csv格式导出):
DATE --- ID --- INITIAL --- FINAL --- MATRICULATION
2017-09-14,"29","2017-09-14 11:00:00","2017-09-14 14:34:00","4"
2017-09-14,"30","2017-09-14 17:00:00","2017-09-14 19:34:00","4"
2017-09-14,"31","2017-09-14 21:00:00","2017-09-14 22:00:00","4"
期望的输出(它是工作时间的总和):
Worked Hours
07:08:00
提前致谢
答案 0 :(得分:1)
要获得所需的结果,您可以使用以下查询
SELECT SEC_TO_TIME(
SUM(
TIMESTAMPDIFF(SECOND,Initial,Final)
)
)
FROM `db_foo` /* WHERE clause*/;
要获得总和以及之前的结果集,您可以按照以下方法
SELECT t.*,SEC_TO_TIME(SUM(workedhours))
FROM (
SELECT ID, TIMESTAMPDIFF(SECOND,Initial,Final) workedhours
FROM `db_foo` /* WHERE clause*/
) t
GROUP BY ID WITH ROLLUP;
答案 1 :(得分:1)
TIME
类型的最大值为838:59:59
。如果您认为总和可能超过838小时,则总结TIME
表达式是不安全的。我建议改为将时差转换为分钟,并以十进制数显示总小时数,而不是时间:
SELECT
ROUND(SUM(TIMESTAMPDIFF(MINUTE, Initial, Final) / 60.0), 1) AS "Worked Hours"
FROM `db_foo`
WHERE matriculation='X' AND date='2017-yy-yy';
会返回
Worked Hours
7.1
答案 2 :(得分:0)
试试这个
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(Final, Initial))))
AS 'Worked Hours'
FROM `db_foo`
WHERE matriculation='X' AND date='2017-yy-yy'
我希望它会对你有所帮助。