Mysql组每隔24小时

时间:2014-01-03 18:06:48

标签: mysql group-by

如何按时间间隔对表格的记录进行分组,从每天19:00开始到第二天18:59结束?

表:测试

id  creation_date   name
1   2014-01-01      17:52:27    a
2   2014-01-01      18:50:00    b
3   2014-01-01      19:00:00    c
4   2014-01-03      18:59:00    e
5   2014-01-03      12:00:00    f

期望的结果是:

Interval                                    Number of Occurrences
2013-31-31 19:00:00 - 2014-01-01 18:59:59   2
2014-01-01 19:00:00 - 2014-01-02 18:59:59   1
2014-01-02 19:00:00 - 2014-01-03 18:59:59   1
2014-01-03 19:00:00 - 2014-01-04 18:59:59   1

2 个答案:

答案 0 :(得分:5)

试试这个:

SELECT MIN(creation_date), MAX(creation_date), COUNT(*) AS Occurrences 
FROM test
GROUP BY DATE(DATE_SUB(creation_date, INTERVAL 19 HOUR))

工作演示:http://sqlfiddle.com/#!2/aa7583/6

对于格式化部分,请使用:

SELECT CONCAT( CONCAT(DATE(DATE_SUB(creation_date, INTERVAL 19 HOUR)),' 19:00:00') , ' - ' , CONCAT(DATE(DATE_ADD(creation_date, INTERVAL 5 HOUR)), ' 18:59:00') ) AS Interval, COUNT(*) AS Occurrences 
FROM test
GROUP BY DATE(DATE_SUB(creation_date, INTERVAL 19 HOUR))

答案 1 :(得分:0)

如下:

 select count( distinct( q0.made_date )) from
 (
     select (date_sub( cast( concat( creation_date, " ", name ) as datetime )), -19, HOUR ) as made_date ) 
 ) as q0

(没有尝试过这个小提琴,但想法是将日期标准化为午夜,然后按日期分组)