80

I have a datetime called activity_dt and the data looks like this:

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

How do i group by date and hour?

felipsmartins
  • 13,269
  • 4
  • 48
  • 56

4 Answers4

145

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 )
Iswanto San
  • 18,263
  • 13
  • 58
  • 79
25

Using MySQL I usually do it that way:

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

Or in the same idea, if you need to output the date/hour:

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;

If you specify an index on your date column, MySQL should be able to use it to speed up things a little.

Simon
  • 3,580
  • 2
  • 23
  • 24
  • I had to replace %h with %H, sorting with 0-24 works better for me instead of 0-12 & 0-12. – Melvin Apr 03 '16 at 09:24
  • Just a note regarding index usage. While date_format does allow indexes to be used, indexes will only be optimally used (loose index scan) when specific/limited aggregate functions are used. Generally, only MIN() and MAX() applied to a single column allow for index scans, and also other aggregates as long as they specify DISTINCT keyword. Source: [link] (http://dev.mysql.com/doc/refman/5.7/en/group-by-optimization.html) – JavoSN Jun 26 '16 at 19:21
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]
DevT
  • 4,843
  • 16
  • 59
  • 92
1

In my case... with MySQL:

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

ggrandes
  • 2,067
  • 22
  • 16