Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql DateTime group by 15 mins

I have a table that looks like this

CREATE TABLE `time_table` (
 `id` INT(10) NOT NULL AUTO_INCREMENT,
 `creationDate` DATETIME NOT NULL,
 PRIMARY KEY (`id`)
)

I basically store the creation time of certain records in the table. I know if I want to get a count of the records that were created in 15 mins interval I will use something like this

SELECT FLOOR(UNIX_TIMESTAMP(creationDate)/900) AS t, 
COUNT(*) FROM time_table
GROUP BY t

That gives me something like this

t          COUNT(*)
1434187    1
1434188    3
1434189    2
1434190    2

How do I make sense of the first column? If I want it to show me something like

t                 COUNT(*)
2:00pm - 2:15pm   1
2:15pm - 2:30pm   3
2:30pm - 2:45pm   2
2:45pm - 3:00pm   2

I understand that with some manipulation I could get 1434187 to show up at 2:15pm. Even that might be a good start....then with some logic I could show the entire period. Thanks!

like image 974
Girish Dusane Avatar asked Nov 27 '10 00:11

Girish Dusane


2 Answers

Here is the solution I use:

SELECT  FROM_UNIXTIME(FLOOR( UNIX_TIMESTAMP(creationDate)/900 ) * 900) AS t, COUNT(*) FROM time_table GROUP BY t

Although it arrives 4 years later, hope it will be useful to someone.

like image 69
Chebe Avatar answered Oct 04 '22 22:10

Chebe


One way is to just use > and < in order to get everything within a range, but you may find this to be simpler:

SELECT ... 

GROUP BY ( 4 * HOUR( thistime ) + FLOOR( MINUTE( thistime ) / 15 )) 

from http://forums.mysql.com/read.php?10,202789,202807

like image 44
James Black Avatar answered Oct 04 '22 21:10

James Black