Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql number of rows per hour

Tags:

mysql

I have a table where each row has a timestamp. Is there a query I can run that can count the number of rows per hour. Outputting a row for each hour with a field for the number of rows encompassed?

e.g

id timestamp

10 2010-09-19 21:05:05

11 2010-09-19 22:05:30

12 2010-09-19 23:05:05

13 2010-09-19 23:05:05

number of rows | hour
1                21
1                22
2                23

I guess there might be problems with using the hour as there will be duplicate hours... so maybe '2010-09-19 21' or just a number representing the period (e.g in the example 2010-09-19 21 is 1)

TIA

like image 869
Starlin Avatar asked Sep 21 '10 15:09

Starlin


People also ask

How to get data for every hour in MySQL?

Here is the SQL query to get data for every hour in MySQL. In the above query, we simply group by order_date using HOUR function and aggregate amount column using SUM function. HOUR function retrieves hour number from a given date/time/datetime value, which can be provided as a literal string or column name.

How do I count rows in MySQL?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.


3 Answers

It depends on how big your date range is. If all dates fall within a month, e.g., you could do this:

select day(timestamp) as Day, hour(timestamp) as Hour, count(*) as Count
from MyTable
where timestamp between :date1 and :date2
group by day(timestamp), hour(timestamp)

You can group by year and month as well if you need to further separate your data.

like image 56
D'Arcy Rittich Avatar answered Nov 07 '22 04:11

D'Arcy Rittich


SELECT HOUR(hour) as hour, COUNT(*) as num_rows FROM `TABLE` GROUP BY HOUR(hour)
like image 22
Pedro Gil Avatar answered Nov 07 '22 04:11

Pedro Gil


Based on D'Arcy Rittich's answer, this worked for me - for months and years:

SELECT YEAR(timestamp), MONTH(timestamp), DAY(timestamp), HOUR(timestamp), COUNT(*) FROM MyTable WHERE timestamp BETWEEN :date1 AND :date2 GROUP BY YEAR(timestamp), MONTH(timestamp), DAY(timestamp), HOUR(timestamp);
like image 1
6opko Avatar answered Nov 07 '22 04:11

6opko