在MySQL中选择按小时分组的日期/时间分组

时间:2010-02-13 19:25:28

标签: php sql mysql datetime

我在mysql表中有一堆日期数据,如下所示:

2010-02-13 1:00:00, "soma data"
2010-02-13 1:25:00, "soma data"
2010-02-13 1:37:00, "soma data"
2010-02-13 2:12:00, "soma data"

我想选择一个显示按小时分组的数据的报告,例如:

On Feb 13, during the hour from 1:00 pm to 1:59 pm, there were 3 data points.
On Feb 13, during the hour from 2:00 pm to 2:59 pm, there was 1 data points.
...

基本上我想报告一天中每小时发生的累计记录数量。所以最终结果会给我一个10天的报告,以24小时为增量进行分析,这样我就可以看到在任何给定的一天中任何给定时间内有多少数据。

TIA,希望你能帮忙!

2 个答案:

答案 0 :(得分:11)

您可能希望使用GROUP BY子句,如以下查询中所示:

SELECT 
    COUNT(*),
    YEAR(dateTimeField),
    MONTH(dateTimeField),
    DAY(dateTimeField),
    HOUR(dateTimeField)
FROM 
    yourTable
WHERE
    dateTimeField >= '2010-02-04 00:00:00' AND
    dateTimeField < '2010-02-14 00:00:00'
GROUP BY 
    YEAR(dateTimeField), 
    MONTH(dateTimeField),
    DAY(dateTimeField),
    HOUR(dateTimeField);

您可能还需要查看MySQL文档以获取有关日期和时间函数的更多参考:

答案 1 :(得分:3)

SELECT HOUR(datetime), COUNT(*)
FROM table
GROUP BY HOUR(datetime);

您将获得两个字段:小时和该小时内的事件数。