简体   繁体   English

MYSQL将日期间隔分组过去10分钟

[英]MYSQL grouping a date interval by past 10 minutes

I have a database with messages and a timestamp field. 我有一个包含消息和时间戳字段的数据库。 I want to select the count for each minute of the past 10 minutes. 我想选择过去10分钟每分钟的计数。 This is my current query: 这是我目前的查询:

SELECT date_format(timestamp, '%H:%i:%s'), COUNT(*) as count
FROM test
WHERE timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND NOW() 
GROUP by
    DATE_FORMAT(timestamp, '%i')
    ORDER BY timestamp ASC

This is almost working as I want it to, showing me the count for the past 10 minutes. 这几乎是我想要的,向我展示过去10分钟的计数。

However, since I'm grouping by the timestamp, for each minute except the very last, I'm getting the count from the first database entry for each minute, making my first and last result much less than the other ones. 但是,由于我按时间戳分组,除了最后一分钟之外的每分钟,我从第一个数据库条目中获取每分钟的计数,使我的第一个和最后一个结果比其他结果少得多。

Like in this image : 就像在这张图片中:

在此输入图像描述

timestamp count 时间戳计数
11:25:35 6 11:25:35 6
11:26:03 11 11:26:03 11
11:27:05 11 11:27:05 11
11:28:01 12 11:28:01 12
11:29:03 12 11:29:03 12
11:30:05 10 11:30:05 10
11:31:01 12 11:31:01 12
11:32:03 12 11:32:03 12
11:33:05 11 11:33:05 11
11:34:01 12 11:34:01 12
11:35:03 5 11:35:03 5

What I am looking for is a way to Group by minutes using something like NOW() instead of my timestamp, like this example. 我正在寻找的是一种使用类似NOW()而不是我的时间戳的分组的方法,就像这个例子一样。

timestamp count 时间戳计数
11:25:35 11 11:25:35 11
11:26:35 12 11:26:35 12
11:27:35 11 11:27:35 11
11:28:35 11 11:28:35 11
11:29:35 11 11:29:35 11
11:30:35 11 11:30:35 11
11:31:35 11 11:31:35 11
11:32:35 11 11:32:35 11
11:33:35 11 11:33:35 11
11:34:35 11 11:34:35 11

在此输入图像描述

Thank you in advance! 先感谢您!

The problem is the WHERE clause. 问题是WHERE子句。 You need to remove the excess seconds before doing the aggregation. 在进行聚合之前,您需要删除多余的秒数。

One method is to convert to seconds, divide by 60, truncate the number, and multiply by 60. The following converts the value back to a date/time value, so an index on that column will be used: 一种方法是转换为秒,除以60,截断数字,然后乘以60.以下将值转换回日期/时间值,因此将使用该列的索引:

SELECT date_format(timestamp, '%H:%i:%s'), COUNT(*) as count
FROM test
WHERE timestamp >= from_unixtime(floor(unix_timestamp(now()) / 60) * 60) - interval 10 minute AND
      timestamp < from_unixtime(floor(unix_timestamp(now()) / 60) * 60)
GROUP BY DATE_FORMAT(timestamp, '%i')
ORDER BY timestamp ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM