Mysql SUM两次,返回总持续时间为天,小时,分钟

时间:2014-10-01 09:14:39

标签: mysql

我想从按行ID分组的多行中选择持续时间。该行包含时间(00:04:25),(00:05:25),(12:04:25)(小时,分钟,秒)等。如何将这些行相加并将总持续时间返回为天,小时, 分钟 ? 我做的是这个(实际上它不是我,我在stackoverflow上的其他帖子中看到了它)

$sql = 'SELECT r.*,d.*,        CONCAT(
        FLOOR(HOUR(SEC_TO_TIME(SUM(TIME_TO_SEC(r.duration)))) / 24), "' . $this-     >_translator->translate(' days ') . '",
        MOD(HOUR(SEC_TO_TIME(SUM(TIME_TO_SEC(r.duration)))), 24), "' . $this->_translator->translate(' hours ') . '",
        MINUTE(SEC_TO_TIME(SUM(TIME_TO_SEC(r.duration)))), "' . $this->_translator->translate(' minutes ') . '") as total_duration, 
        ROUND(SUM(TIME_TO_SEC(r.duration)/3600)) as total_duration_hours FROM routes r LEFT JOIN drivers d ON d.id = r.driver_id GROUP BY r.driver_id';

这是不正确的。在r。*中也存储了平均速度,距离,例如,此代码返回2小时,23分钟时应返回2小时30分钟。请帮忙。谢谢!

编辑: 以下是一些数据:

 Full texts     id  filename    distance    startRoute  endRoute    duration    avgSpeed    car_id  fromLocation    toLocation  driver_id
Edit Edit   Copy Copy   Delete Delete   748     GPSdata20140109073948   5.74    2014-01-09 07:40:23     2014-01-09 07:50:38     00:10:15    33.6    20  22, Ulhaus, Langerwehe  27, Königsbenden, Eschweiler   18
Edit Edit   Copy Copy   Delete Delete   754     GPSdata20140110182521   1.43    2014-01-10 18:25:26     2014-01-10 18:29:31     00:04:05    21.01   18  36, Grüner Weg, Aachen     3, Rehmplatz, Aachen    18
Edit Edit   Copy Copy   Delete Delete   758     GPSdata20140112145245   70.55   2014-01-12 14:54:05     2014-01-12 16:54:42     02:00:37    35.09   23  275, Hauptstraße, Langerwehe   , Pescher Weg, Cologne  18
Edit Edit   Copy Copy   Delete Delete   759     GPSdata20140113072802   6.17    2014-01-13 07:28:37     2014-01-13 07:37:02     00:08:25    43.98   19  13, Bahnhofstraße, Langerwehe  27, Königsbenden, Eschweiler   18

5.74 + 1.43 + 70.55 + 6.17 = 83.9距离 33.6 + 21.01 + 35.09 + 43.98 =平均速度33.42 所以距离/平均速度= 2小时30分钟,我得到2小时23分钟。我在哪里做错了?

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询来获得所需的结果:

select CONCAT(FLOOR(time_in_sec/(60*60*24))," days " ,
FLOOR((time_in_sec/(60*60*24) - FLOOR(time_in_sec/(60*60*24)))*24)," hours ",
FLOOR(((time_in_sec/(60*60*24) - FLOOR(time_in_sec/(60*60*24)))*24 - 
FLOOR((time_in_sec/(60*60*24) - 
FLOOR(time_in_sec/(60*60*24)))*24))*60)," minutes" ) total_duration

FROM (
select SUM(TIME_TO_SEC(r.duration)) time_in_sec 
from routes r LEFT JOIN drivers d ON d.id = r.driver_id 
GROUP BY r.driver_id') T;

查询的逻辑如下:
1.总和秒数并将其存储在变量time_in_sec中。使用此结果来自:

FROM (
    select SUM(TIME_TO_SEC(r.duration)) time_in_sec 
    from routes r LEFT JOIN drivers d ON d.id = r.driver_id 
    GROUP BY r.driver_id') T;
  1. 休息是纯粹的数学 a。)连续几天:楼层(time_in_sec / 3600) b。)小时:楼层((time_in_sec / 3600 - 天)* 24)
    c。)分钟:楼层(((time_in_sec / 3600 - 天)* 24小时)* 60)