如何计算线之间的平均时差?

时间:2013-05-10 09:56:00

标签: mysql

我有一个mysql表'totolog':

id  dt                    data
1   2013-05-01 06:01:01   hi john  
2   2013-05-01 06:04:23   hi bob  
3   2013-05-01 07:17:36   hi alex  
4   2013-05-01 14:49:41   hi all  

如何检索行之间的平均时差?

我怀疑这样的事情:

SELECT UNKNOW_FUNCTION(dt) FROM totolog ORDER BY dt ASC;

2 个答案:

答案 0 :(得分:1)

平均时间为time_max - time_min / number_of_records

SELECT (max(dt) - min(dt)) / count(dt) as avg_dt
FROM totolog 
ORDER BY avg_dt ASC;

答案 1 :(得分:1)

给定像这样的数据集......

CREATE TABLE totolog
 (id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY
 ,dt                    DATETIME NOT NULL
 ,data VARCHAR(20) NOT NULL
 );

 INSERT INTO totolog VALUES
 (1   ,'2012-12-01 06:01:01','hi john'),
 (2   ,'2013-01-01 06:04:23','hi bob'),
 (3   ,'2013-02-01 07:17:36','hi alex'),
 (4   ,'2013-03-28 14:49:41','hi all');

我想你会想要这样的......

SELECT FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(dt)))x FROM totolog;
+---------------------+
| x                   |
+---------------------+
| 2013-01-22 20:33:10 |
+---------------------+
1 row in set (0.00 sec)

......或者......

SELECT FROM_UNIXTIME((MAX(UNIX_TIMESTAMP(dt))+MIN(UNIX_TIMESTAMP(dt)))/2)x 
  FROM totolog;
+---------------------+
| x                   |
+---------------------+
| 2013-01-28 22:25:21 |
+---------------------+
1 row in set (0.00 sec)