如何按5秒间隔选择和分组日期?

时间:2014-05-05 03:36:07

标签: mysql sql

我在选择和分组时间方面遇到了问题 例如,我在数据库中得到以下时间:

2014-03-31 00:00:06
2014-03-31 00:00:06
2014-03-31 00:00:06
2014-03-31 00:00:16
2014-03-31 00:00:16
2014-03-31 00:00:16
2014-03-31 00:00:22
2014-03-31 00:00:22
2014-03-31 00:00:22
2014-03-31 00:00:26
2014-03-31 00:00:26
2014-03-31 00:00:26
2014-03-31 00:00:39
2014-03-31 00:00:39
2014-03-31 00:00:39
2014-03-31 00:00:42
2014-03-31 00:00:42
2014-03-31 00:00:42
2014-03-31 00:00:49
2014-03-31 00:00:49
2014-03-31 00:00:49
2014-03-31 00:00:58
2014-03-31 00:00:58
2014-03-31 00:00:58
2014-03-31 00:01:30
2014-03-31 00:01:30
2014-03-31 00:01:30
2014-03-31 00:01:39
2014-03-31 00:01:39
2014-03-31 00:01:39
2014-03-31 00:01:40
2014-03-31 00:01:40
2014-03-31 00:01:40
2014-03-31 00:01:47
2014-03-31 00:01:47
2014-03-31 00:01:47
2014-03-31 00:02:06
2014-03-31 00:02:06
2014-03-31 00:02:06
2014-03-31 00:02:09

我想以5 seconds的间隔对它们进行分组并计算它们 例如。

2014-03-31 00:00:00   Count 0
2014-03-31 00:00:05   Count 3
2014-03-31 00:00:10   Count 0
2014-03-31 00:00:15   Count 3
2014-03-31 00:00:20   Count 3
etc....

我尝试过使用date_format,似乎无法按预期对它们进行分组。

感谢所有SOers。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT   sec_to_time(time_to_sec(col1)- time_to_sec(col1)%(5)) AS timekey, count(*)
FROM     mytable
GROUP BY timekey;

小提琴示例: SQL Fiddle

答案 1 :(得分:0)

  select concat(date_format(dt,'%Y-%m-%d H:%i:'),lpad(floor(second(dt)/5)*5,2,'0')), count(*)
    from dates 
group by concat(date_format(dt,'%Y-%m-%d %H:%i:'),lpad(floor(second(dt)/5)*5,2,'0'));