Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group MySQL Data into Arbitrarily Sized Time Buckets

Tags:

time

mysql

How do I count the number of records in a MySQL table based on a timestamp column per unit of time where the unit of time is arbitrary?

Specifically, I want to count how many record's timestamps fell into 15 minute buckets during a given interval. I understand how to do this in buckets of 1 second, 1 minute, 1 hour, 1 day etc. using MySQL date functions, e.g.

SELECT YEAR(datefield) Y, MONTH(datefield) M, DAY(datefield) D, COUNT(*) Cnt FROM mytable GROUP BY YEAR(datefield), MONTH(datefield), DAY(datefield)

but how can I group by 15 minute buckets?

like image 988
Eric J. Avatar asked Apr 05 '10 17:04

Eric J.


3 Answers

GROUP BY
    YEAR(datefield),
    MONTH(datefield),
    DAY(datefield),
    HOUR(datefield),
    FLOOR(MINUTE(datefield)/15)

You could alternatively say just:

SELECT FLOOR(UNIX_TIMESTAMP(datefield)/900) AS t, COUNT(*) AS cnt
FROM mytable
GROUP BY t

with the application responsible for formatting the timestamp for each 15-minute period back out to readable y/m/d/h/m. (If you needed to have local time in a crazy non-quarter-hour-aligned timezone, you'd need a hack offset though.)

like image 122
bobince Avatar answered Oct 19 '22 03:10

bobince


How about getting the INTEGER of ( HOUR( DateField ) * 60 + MINUTES( DateField )) / YourInterval.

This way, no matter what your interval, by including the hour * 60 minutes will keep it sequentially during a given day and you won't be dealing with just 15 minutes grouped per hour, but each 15 minutes of its OWN hour... Add that column to your group by clause which you can do by its ordinal position.

like image 34
DRapp Avatar answered Oct 19 '22 03:10

DRapp


Just to get you thinking, here's an alternative to the FLOOR(MINUTE(datefield)/15) solution:

GROUP BY CASE
WHEN MINUTES(datetime) BETWEEN 0 AND 14 THEN 0
WHEN MINUTES(datetime) BETWEEN 15 AND 29 THEN 1
WHEN MINUTES(datetime) BETWEEN 30 AND 44 THEN 2
WHEN MINUTES(datetime) BETWEEN 45 AND 59 THEN 3
END
like image 37
Marcus Adams Avatar answered Oct 19 '22 03:10

Marcus Adams