我有以下表结构和数据
DriverName CarType StartTime EndTime
---------- ------- --------- --------
DriverA Honda 2014-09-29 14:32:03 2014-09-29 14:48:09
DriverA Honda 2014-09-29 12:32:03 2014-09-29 14:32:09
DriverA Honda 2014-09-29 10:32:03 2014-09-29 14:32:09
DriverA Toyota 2014-09-29 10:32:03 2014-09-29 10:34:09
DriverA Toyota 2014-09-29 9:32:03 2014-09-29 9:39:09
DriverA Toyota 2014-09-29 8:32:03 2014-09-29 8:52:09
如何以秒/分钟/小时
获得最差的最佳和平均时间DriverName CarType Worst Best
---------- -------- ------ -----
DriverA Honda 04:00:06 (4 hrs 6 seconds) 00:04:06 (4 minutes 3 seconds)
DriverA Toyota 00:20:06 (4 hrs 6 seconds) 00:2:06 (20 minutes 3 seconds)
答案 0 :(得分:1)
为了得到最好和最差,你会想要在开始时间和结束时间之间获得日期差异,然后分别获得最小值或最大值,然后对于平均值,你基本上可以做同样的但是使用平均值功能。最后你会想要分类CarType和(我认为)驱动程序这里是一个例子:
修改强>
有人指出DATEDIFF
没有按照我的预期运作,它会在几天内明确返回差异,我已经更新了查询以使用TIMEDIFF
代替,我还添加了使用TIME_TO_SEC()
函数直接在几秒钟内提供输出。
SELECT DriverName,
CarType,
MAX(TIME_TO_SEC(TIMEDIFF(EndTime,StartTime))) AS 'Worst',
MIN(TIME_TO_SEC(TIMEDIFF(EndTime,StartTime))) AS 'Best',
AVG(TIME_TO_SEC(TIMEDIFF(EndTime,StartTime))) AS 'Average'
GROUP BY DriverName, CarType
答案 1 :(得分:1)
您可能想要使用timestampdiff()
select DriverName, CarType,
min(timestampdiff(second, StartTime, EndTime)) as Best,
max(timestampdiff(second, StartTime, EndTime)) as Worst
from followingtable ft
group by DriverName, CarType;
如果要将值显示为时间格式:
select DriverName, CarType,
date_format(cast(0 as datetime) + interval min(timestampdiff(second, StartTime, EndTime,)) second,
'%H:%m:%d) as Best,
date_format(cast(0 as datetime) + interval max(timestampdiff(second, StartTime, EndTime)) second,
'%H:%m:%d') as Worst
from followingtable ft
group by DriverName, CarType;