MySQL / MariaDB:如何找到基于时间的数据的空白?

时间:2018-08-23 09:52:36

标签: mysql syntax

记录器系统每5秒钟保存一行数据(秒== 0,5,10,15,...,55;不可能像23:00:07这样的时间)。

有时记录器由于通讯错误而无法保存,并且表中只是缺少行。

我需要检测这些间隙:我想读取间隙之前的最后一行和间隙之后的第一行。

这些是演示数据:

create table #time (
    DateTime datetime not null,
    Value int not null
);

insert into #time (DateTime, Value)
    values
        ('2018-08-23 00:00:00', 123),
        ('2018-08-23 00:00:05', 152),
        ('2018-08-23 00:00:10',  37),
        ('2018-08-23 00:00:15', 141),
        ('2018-08-23 00:00:20',  41),
        ('2018-08-23 00:00:25',  35),
        ('2018-08-23 00:00:30', 143),
        ('2018-08-23 00:00:35',  67),
        ('2018-08-23 00:00:40', 111),
                                        /* gap of one minute here */
        ('2018-08-23 00:01:45', 123),
        ('2018-08-23 00:01:50', 145),
        ('2018-08-23 00:01:55', 141),
        ('2018-08-23 00:02:00',  87),
                                        /* gap of 10 seconds here */
        ('2018-08-23 00:02:15', 190),
        ('2018-08-23 00:02:20', 122),
        ('2018-08-23 00:02:25', 123);

select * from #time;

它们也在RexTester

我想回读:

    GapStart              GapEnd                Size
0   2018-08-23 00:00:40   2018-08-23 00:01:45   0000-00-00 00:01:45
1   2018-08-23 00:02:00   2018-08-23 00:02:15   0000-00-00 00:00:15

当然不应列出5秒的间隔

我发现的内容被称为同一行中的开始/结束日期时间(Find gaps in timesheet data between certain hours),或者对我来说太复杂了 以至于无法适应我的情况(find gaps in sequential dates )。

我正在使用MariaDB 10.0.28(无法升级):这意味着LAG()不可用。

提前谢谢

1 个答案:

答案 0 :(得分:1)

一种方法可能是先进行子查询,然后将每个记录与时间戳最近的较大记录配对。然后,进行查询,并返回所有具有足够大小的间隙的记录。

SELECT
    DateTime AS GapStart,
    NextDateTime AS GapEnd,
    TIMESTAMPDIFF(SECOND, DateTime, NextDateTime) AS SizeInSecond
FROM
(
    SELECT DateTime, Value,
        (SELECT MIN(DateTime) FROM #time t2
         WHERE t2.DateTime > t1.DateTime) AS NextDateTime
    FROM #time t1
) t
WHERE
    TIMESTAMPDIFF(SECOND, DateTime, NextDateTime) > 5;   -- or whatever threshhold you want

enter image description here

Demo

添加到原始答案

如果DateTime一直在增长,则可以通过更改内部SELECT来提高速度:

SELECT
    DateTime AS GapStart,
    NextDateTime AS GapEnd,
    TIMESTAMPDIFF(SECOND, DateTime, NextDateTime) AS SizeInSecond
FROM
(
    SELECT DateTime, Value,
        (SELECT DateTime FROM #time t2
         WHERE t2.DateTime > t1.DateTime LIMIT 1) AS NextDateTime
    FROM #time t1
) t
WHERE
    TIMESTAMPDIFF(SECOND, DateTime, NextDateTime) > 5;