Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

sql - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...