2013-11-09 68 views
0

請看下面的測試數據。我想獲取avgtime(= timeonsite/visits)並在mysql中顯示爲「xx:xx:xx」結果。我怎麼才能得到它?如何在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

回答

1

相信您在這樣的方式avgtime計算? 如果是,MySQL的選擇如下:

select id, timeOnsite,visits, SEC_TO_TIME(TIME_TO_SEC(timeOnsite)/visits) as avgtime 
from t 
+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