如何以五分钟为间隔获取今天的记录数量?

时间:2015-12-28 12:14:04

标签: mysql sql

假设我在名为creation_timestamp的表上有一个名为bank_payments的列,我想今天打破五分钟的间隔,然后在每个间隔中查询数据库中的计数。

我将手动阅读此内容(即这不适合应用程序使用),因此输出格式无关紧要,只要我可以使用它来获取五分钟的时间段,并且那个时期的记录。

是否可以完全在数据库一侧执行此操作?

3 个答案:

答案 0 :(得分:2)

如果您希望按照5分钟的间隔按表中的记录分组,那么您可以尝试:

SELECT col1, count(col1), creation_timestamp
FROM bank_payments
WHERE DATE(`creation_timestamp`) = CURDATE()
GROUP BY UNIX_TIMESTAMP(creation_timestamp) DIV 300, col1

答案 1 :(得分:1)

是。这是一种方法:

select sec_to_time(floor(time_to_sec(time(datetimecol)*5/60))), count(*)
from t
where t.datetimecol >= curdate() and
      t.dattimeecol < curdate() + interval 1 day
group by 1
order by 1;

答案 2 :(得分:1)

如果您期望输出

|          begin_time |            end_time | cnt |
|---------------------|---------------------|-----|
|          2015-12-28 | 2015-12-28 00:05:00 |   1 |
| 2015-12-28 01:00:00 | 2015-12-28 01:05:00 |   4 |
| 2015-12-28 01:05:00 | 2015-12-28 01:10:00 |   1 |
| 2015-12-28 02:55:00 | 2015-12-28 03:00:00 |   4 |
| 2015-12-28 03:05:00 | 2015-12-28 03:10:00 |   1 |
| 2015-12-28 03:10:00 | 2015-12-28 03:15:00 |   1 |

然后

select
    begin_time,
    end_time,
    sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) cnt
from (
    select @r begin_time, @r := @r + INTERVAL 5 MINUTE end_time
    from (select @r := curdate()) r,
    (select 1 union all select 1 union all select 1 union all select 1) a1, #4
    (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1) a2, #6 * 4 = 24
    (select 1 union all select 1 union all select 1 union all select 1) a3, #4 * 24 =  96
    (select 1 union all select 1 union all select 1) a4 #3 * 96 =  288
) x,
(select creation_timestamp from bank_payments) y
group by begin_time, end_time 

如果您只需要那些有计数的间隔&gt; 0然后

select
    begin_time,
    end_time,
    sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) cnt
from (
    select @r begin_time, @r := @r + INTERVAL 5 MINUTE end_time
    from (select @r := curdate()) r,
    (select 1 union all select 1 union all select 1 union all select 1) a1, #4
    (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1) a2, #6 * 4 = 24
    (select 1 union all select 1 union all select 1 union all select 1) a3, #4 * 24 =  96
    (select 1 union all select 1 union all select 1) a4 #3 * 96 =  288
) x,
(select creation_timestamp from bank_payments) y
group by begin_time, end_time 
having sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) > 0

sql fiddle demo