Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Getting "busiest" or "most popular" hour from a datetime field?

Consider the following table which has the fields - id (int) and date_created (datetime):

id       date_created

 1       2010-02-25 12:25:32
 2       2010-02-26 13:40:37
 3       2010-03-01 12:02:22
 4       2010-03-01 12:10:23
 5       2010-03-02 10:10:09
 6       2010-03-03 12:45:03

I want to know the busiest/most popular hour of the day for this set of data. In this example, the result I'm looking for would be 12.

Ideas?

like image 530
k00k Avatar asked Mar 18 '10 16:03

k00k


People also ask

Can we extract date from timestamp in SQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.

How do I select timestamp from time in SQL?

The syntax for DATE_TRUNC , time_column is the database column that contains the timestamp you'd like to round, and '[interval]' dictates your desired precision level. Let's assume our NOW() returns the same 2020–03–29 00:27:51.677318+00:00, we can use date_part to get the following.

How do you get just the time from a datetime in SQL?

How do you get just the time from a DateTime in SQL? SELECT GETDATE();– Output: 2019-03-31 08:12:08.600. SELECT CAST('2019–03–31 08:12:08.600' AS TIME)– Output: 08:12:08.6000000. SELECT CONVERT(VARCHAR(10), CAST('2019–03–31 08:12:08.600' AS TIME), 0)– Output: 8:12AM.

What is Getdate () in MySQL?

The GETDATE function is used to retrieve the current database system time in SQL Server. A common use of GETDATE is to get today's date.


1 Answers

To get just the most popular hour, use this query

select date_format( date_created, '%H' ) as `hour`
  from [Table]
 group by date_format( date_created, '%H' )
 order by count(*) desc
 limit 1;

If you want to look at all the data, go with this one

select count(*) as num_records
     , date_created
     , date_format( date_created, '%H' ) as `hour`
  from [Table]
 group by `hour`
 order by num_records desc;
like image 127
Peter Bailey Avatar answered Sep 23 '22 01:09

Peter Bailey