如何在mysql中按小时总结

时间:2015-03-01 07:54:47

标签: mysql sql group-by

例如,我有一个table1(这只是table1的一部分,table1实际上有57000条记录,开始时间范围从2014-04-08 23:59:56到2014-04-09 23:59:56) :

+---------------------+
| StartTime           |
+---------------------+
| 2014-04-08 23:59:56 |
| 2014-04-08 23:59:59 |
| 2014-04-09 00:00:03 |
| 2014-04-09 00:00:03 |
| 2014-04-09 00:00:05 |
| 2014-04-09 00:00:08 |
| 2014-04-09 00:00:09 |
| 2014-04-09 00:00:11 |
| 2014-04-09 00:00:11 |
| 2014-04-09 00:00:17 |
+---------------------+

该表是关于网络流量的,开始时间是指每个流量的开始时间。一些网络流量具有相同的开始时间。我想计算每小时流量。 伪代码就像

select count(starttime) as totalPerHour from table1 group by hour; 
(just pseudo-code)
The result should be:
  TimestampHOUR       totalPerHour
  2014-04-09 01:00       46
  2014-04-09 02:00       3
  2014-04-09 03:00       55
  2014-04-09 04:00       12
  2014-04-09 05:00       2369
  2014-04-09 06:00       99

2 个答案:

答案 0 :(得分:1)

MySQL有hour(..)。使用它像:

select count(*) as totalPerHour from table1 group by HOUR(StartTime);

答案 1 :(得分:1)

结合小时(...)和计数(..)

select hour(StartTime), count(StartTime)
from table1
group by hour(StartTime)