4

Possible Duplicate:
Group records by time

I have a mysql table that logs web page requests.

I'd like to write a sql that outputs the number of requets per hour.

INPUT:
timestamp              browser
-------------------    -------
2012-06-28 15:06:14    chrome
2012-06-28 15:12:15    IE6
2012-06-28 16:32:16    IE7

OUTPUT:
timestamp              count
-------------------    -------
2012-06-28 15:00:00    2
2012-06-28 16:00:00    1

I'm guessing my first step would be to 'truncate' the datetime field so that I can do a group-by. Searching, I have found some examples of rounding the hour, but none to truncate.

Community
  • 1
  • 1
Eric
  • 2,900
  • 2
  • 19
  • 20
  • See: http://stackoverflow.com/questions/10110341/group-records-by-time – David Manheim Jun 28 '12 at 13:54
  • That question is not an exact duplicate, it groups by 15 minute intervals. In addtion, the answers here are also not duplicates, as they use the date_format functions which are not used in answers to the other question... To merge these, both the questions and answers would need to be modified. – Eric Aug 09 '12 at 12:48

4 Answers4

5
select count(no_of_requests) from table group by date(datetime_field) , hour(datetime_field)
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
4

Try formatting the date with

DATE_FORMAT(timestamp, '%Y-%m-%d %H') as formatted_timestamp

and then grouping on that formatted_timestamp

Ekster
  • 353
  • 1
  • 4
3

Assuming ts_table as your table name and ts as your timestamp column name,

mysql> select
    ->     addtime( date_format( ts, '%Y-%m-%d %H' ), '00:00:00' ) as 'during'
    ->     , count( date_format( ts, '%Y-%m-%d %H' ) ) as 'visit_count'
    -> from ts_table
    -> group by 'during'
    -> ;
+---------------------+-------------+
| during              | visit_count |
+---------------------+-------------+
| 2012-06-28 15:00:00 |           2 |
| 2012-06-28 16:00:00 |           1 |
+---------------------+-------------+
2 rows in set (0.00 sec)
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
1

You should be able to group by DATE() and HOUR() functions to get your output.

pedromarce
  • 5,651
  • 2
  • 27
  • 27