Question

I'm new to SQL Datetime.

Considering I have records in MySQL with Datetime data (as seen below), what is the best way to get the most frequent occurring HOUR or range/period for these records for a particular user (i.e. john)?

ID      | Datetime            | User      | Activity
0    2010-03-29 13:15:56        john         visit
1    2010-03-29 13:13:14        ariel        visit
2    2010-03-29 13:09:13        john         visit
3    2010-03-29 13:07:21        john         visit
4    2010-02-23 12:21:03        john         visit
5    2010-02-23 12:01:03        john         visit
6    2010-02-23 11:01:03        john         visit
7    2010-02-23 02:01:03        john         visit

With the above data, the frequent hour for john doing visit would be 13, while period would be perhaps 12-13.

The goal is to find the period/time that the user does a certain activity most.

Thanks in advance for all the help!

Was it helpful?

Solution

It can depend on the database you're using, but in mysql :

SELECT COUNT(id) as count, HOUR(Datetime) as hour FROM table GROUP BY hour ORDER BY count DESC LIMIT 1

(see http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)

OTHER TIPS

with oracle you can write something like

select TO_CHAR(Datetime, 'HH24'), count(ID) from Table group by TO_CHAR(Datetime, 'HH24')

on other RDBMS use equivalent function to extract hour part from Datetime field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top