mysql选择具有时间间隔的记录数

标签 mysql

尝试在具有日期时间列 (abc_datetime) 的表上执行简单的选择计数 ()。但是,我想为日期时间值比任何其他行的日期时间值晚至少 15 分钟的那些行返回一个计数 ()。这个想法是我想忽略第一行 15 分钟内具有日期时间值的任何后续行。

Table Test
+---------------------+
| abc_datetime        |
+---------------------+
| 2014-07-21 00:49:52 |
| 2014-07-21 01:49:50 |
| 2014-07-21 02:49:45 |
| 2014-07-21 03:49:39 |
| 2014-07-21 04:49:38 |
| 2014-07-21 05:49:32 |
| 2014-07-21 06:49:24 |
| 2014-07-21 07:49:20 |
| 2014-07-21 08:49:14 |
| 2014-07-21 09:00:16 |
| 2014-07-21 09:00:25 |
| 2014-07-21 09:50:55 |
| 2014-07-21 09:51:03 |
| 2014-07-21 09:51:33 |
| 2014-07-21 09:51:46 |
| 2014-07-21 10:51:36 |
| 2014-07-21 11:51:30 |
| 2014-07-21 12:51:22 |
| 2014-07-21 13:51:12 |
| 2014-07-21 14:51:05 |
| 2014-07-21 15:50:55 |
+---------------------+
21 rows in set (0.01 sec)
想要返回 18 的计数,因为来自 09:00:25 和 09:51:XX 的日期时间记录将在计数中被忽略,因为它们在前一行的日期时间值的 15 分钟内。

最佳答案

我会为此使用相关子查询:

select count(*)
from (select t.*,
             (select t2.abc_datetime
              from test t2
              where t2.abc_datetime < t.abc_datetime
              order by t2.abc_datetime
              limit 1
             ) as prev_dt
      from test t
     ) t
where prev_dt is null or prev_dt < abc_datetime - interval 15 minute;

你也可以使用不存在来做到这一点:

select count(*)
from test t
where not exists (select 1
                  from test t2
                  where t2.abc_datetime < t.abc_datetime and
                        t2.abc_datetime >= t.abc_datetime - interval 15 minute
                 );

我更喜欢这个版本,因为它只是为了获得计数。第一个版本更适合实际查看值。

关于mysql选择具有时间间隔的记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24876761/

相关文章:

mysql - 在MYSQL中将文本转换为tinyint

java - 如何将列的值设置为列表中实体的位置索引?

mysql - 如果列值不存在,SQL INSERT 新行

mysql - Saiku 在 Openshift 和 mysql 连接问题上的实现

php - MySQL - 将 INT 转换为 DATE 格式。

java - 用户 'root' @'localhost' 的访问被拒绝(使用密码 : YES): PhpMyAdmin

php - 如何使用 PHP 中的过程获取数据?

java - Spring hibernate 不需要的时区调整

MYSQL - 将多个用户添加到表列

php - 如何修复 "Illuminate\Database\QueryException: SQLSTATE[HY000] [1044] Access denied for user"