如何在mysql上获得平均时间'xx:xx:xx'?

时间:2013-11-09 07:59:23

标签: mysql

请参阅下面的测试数据。我想获得avgtime(= timeonsite / visits)并在mysql中显示为“xx:xx:xx”结果。我怎么能得到它?

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t`
-- ----------------------------
DROP TABLE IF EXISTS `t`;
CREATE TABLE `t` (
  `id` int(11) NOT NULL auto_increment,
  `timeOnsite` time default NULL,
  `visits` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t
-- ----------------------------
INSERT INTO `t` VALUES ('1', '04:05:30', '20');
INSERT INTO `t` VALUES ('2', '03:00:00', '10');
INSERT INTO `t` VALUES ('3', '00:01:30', '17');

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用TIME_TO_SEC功能将xx:xx:xx格式更改为秒。

SELECT TIME_TO_SEC('00:01:30') / 17;  # return 5.2941

然后通过SEC_TO_TIME,您可以将秒转换为时间,如下所示:

SELECT SEC_TO_TIME(TIME_TO_SEC('00:01:30') / 17);  # return 00:00:05

答案 1 :(得分:1)

请确保以这种方式计算平均时间? 如果是,请在下面选择mysql:

select id, timeOnsite,visits, SEC_TO_TIME(TIME_TO_SEC(timeOnsite)/visits) as avgtime
from t