添加时间并获得PHP的平均值

时间:2014-04-08 02:15:03

标签: php mysql

我的数据库上有这个表。

+--------- --------- ------------+
|   id    |   time  |    date    |
+--------- --------- ------------+
|    1    |   0:12  | 03/30/2014 |
 --------- --------- ------------
|    2    |   0:14  | 04/09/2014 | <-- date today
 --------- --------- ------------
|    3    |   0:32  | 04/09/2014 | <-- date today
 --------- --------- ------------
|    4    |   0:24  | 04/09/2014 | <-- date today
 --------- --------- ------------

时间只有几分钟和几秒钟。我想得到时间的总和,得到平均值。平均计数取决于今天添加的新记录数量为3。

今天(04/09/2014)= 3

的记录数/秒

今天的新时间记录:

0:14
0:32
0:24

今天的总时间= 1:10

Average = 1:10 / 3

1 个答案:

答案 0 :(得分:0)

MySQL解决方案

select 
    avg( str_to_date( time, '%i:%s' ) ) 'avg t in sec', 
    date(date) date
from entries 
group by 2;

演示 @ MySQL 5.6.6 Fiddle

在我的控制台上观察到的结果

mysql> select
    ->   sum( str_to_date( time, '%i:%s' ) ) t,
    ->   date
    -> from entries
    -> group by 2;
+------+---------------------+
| t    | date                |
+------+---------------------+
|   12 | 2014-03-30 00:00:00 |
|   70 | 2014-04-09 00:00:00 |
+------+---------------------+
2 rows in set (0.00 sec)

mysql> select
    ->     avg( str_to_date( time, '%i:%s' ) ) 'avg t in sec',
    ->     date(date) date
    -> from entries
    -> group by 2;
+--------------+------------+
| avg t in sec | date       |
+--------------+------------+
|      12.0000 | 2014-03-30 |
|      23.3333 | 2014-04-09 |
+--------------+------------+
2 rows in set (0.00 sec)