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?
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.
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? 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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With