DateTime按日期和小时分组

时间:2013-02-13 03:36:18

标签: mysql sql

我有一个名为 activity_dt 的日期时间,数据如下所示:

2/5/2013 9:24:00 AM
2/7/2013 7:17:00 AM

我如何按日期和小时分组?

4 个答案:

答案 0 :(得分:70)

SQL Server:

SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);

Oracle:

SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');

MySQL:

SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )

答案 1 :(得分:12)

使用MySQL我通常这样做:

SELECT count( id ), ...
FROM quote_data
GROUP BY date_format( your_date_column, '%Y%m%d%H' )
order by your_date_column desc;

或者在同一个想法中,如果你需要输出日期/小时:

SELECT count( id ) , date_format( your_date_column, '%Y-%m-%d %H' ) as my_date
FROM  your_table 
GROUP BY my_date
order by your_date_column desc;

如果在日期列中指定索引,MySQL应该可以使用它来加速一些事情。

答案 2 :(得分:1)

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

答案 3 :(得分:0)

就我而言...使用MySQL:

SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))