我想从按某个 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 分钟。我哪里做错了?
最佳答案
您可以使用以下查询来获得所需的结果:
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;
- 休息是纯数学。
a.)天数:下限(time_in_sec/3600)。
b.)小时数:下限((time_in_sec/3600 - 天)*24)
c.)分钟:Floor(((time_in_sec/3600 - 天)*24 - 小时)*60)
关于Mysql SUM 两次并返回总持续时间为天、小时、分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26137944/