Mysql DateTime group by 15 mins

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-17 19:47:08

问题


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!


回答1:


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




回答2:


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.




回答3:


Answer 2 only works for 24hours - try this one;

SELECT ...

GROUP BY year(date),month(date),day(date),( 4 * HOUR( date ) + FLOOR( MINUTE( date ) / 15 )) 


来源:https://stackoverflow.com/questions/4289345/mysql-datetime-group-by-15-mins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!