高级MySQL时间总和

时间:2014-04-07 12:32:16

标签: mysql sql time sum

我有MySQL查询工作正常并返回多行时间值。我正在寻找将所有时间值相加并将它们作为单行返回的可能性。

所以查询是这样的:

SELECT TIMEDIFF('24:00:00',(TIMEDIFF('22:00:00',TIME(end)))) AS time
FROM sn_workingtime
WHERE user='magdalena'
AND type='work'
AND start >= '2014-03-01' AND start <= '2014-03-31 23:59:59'
AND (HOUR(`end`) > 22 OR HOUR(`end`) < 4)
AND completed=1

此查询返回:

time
02:02:36
03:17:24
03:07:03
02:24:17
03:14:09

我希望此查询在sigle行中返回以下所有时间值的总和,如下所示:

time
14:05:29

有没有办法让MySQL“自动”求和结果集?谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个我的朋友,你可以转换你的time to seconds,然后将所有秒数相加,最后转换为seconds to time

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(t.time))) as time FROM 
(SELECT TIMEDIFF('24:00:00',(TIMEDIFF('22:00:00',TIME(end)))) AS time
FROM sn_workingtime
WHERE user='magdalena'
AND type='work'
AND start >= '2014-03-01' AND start <= '2014-03-31 23:59:59'
AND (HOUR(`end`) > 22 OR HOUR(`end`) < 4)
AND completed=1)t;

看一看 here

答案 1 :(得分:0)

当然,只使用没有GROUP BY的聚合函数,它将聚合所有行。例如:

SELECT SUM(time) FROM (
   -- your query goes here
) x