【问题标题】:Find gaps in mysql Time查找 mysql 时间中的空白
【发布时间】:2015-02-08 14:21:18
【问题描述】:

我有一个带有时间戳列 Time 的表“channel_001”,我确实将它分开了 10 分钟。

2013-01-01;00:10:04;
2013-01-01;00:20:00;
2013-01-01;00:30:02;
2013-01-01;00:40:04;

但是缺少数据。如何检测缺失的行?然后在那里插入一行?!

例如:

2013-01-01;00:10:04;
2013-01-01;00:20:00;
2013-01-01;00:30:02
2013-01-01;00:40:04;
2013-01-01;01:00:02;

那么它就会丢失:

2013-01-01;00:50:00;

我正在考虑使用将表加入自身,但我是 SQL 新手,而且新手太多,无法单独找到答案。

有什么想法吗?

【问题讨论】:

  • 为什么缺少行?那个分号是什么?
  • 分号因为输出格式:分隔文本。这些数据是单个设备消耗的有功功率。有时:当没有人在家时 -> 没有数据被记录。或者这是一个错误。
  • 但是为什么要先检查呢?
  • 因为我预测的准确性,我会用 MATLAB 做什么。

标签: mysql


【解决方案1】:

您可以通过以下方式找到没有“下一次”时间的行:

select c.*
from channel_001 c
where not exists (select 1
                  from channel_001 c2
                  where c2.timestamp > c.timestamp + interval 9 minute and
                        c2.timestamp < c.timestamp + interval 11 minute
                 );

如果您的表很大(数万行),您可能需要使用变量。以下代码获取之前的时间戳:

select c.*,
       (case when (@tmp := @prevts) is null then null
             when (@prevts := timestamp) is null then null
             else @tmp
        end) as prev_timestamp
from channel_001 c cross join
     (select @prevts := 0, @tmp := 0) vars
order by timestamp;

您可以将其用作子查询来获取超出范围的间隙。

【讨论】:

  • 为了将数据分隔 10 分钟,我确实写了:选择 DATE(time) 作为 Date,DATE_FORMAT(time,'%T') 作为 Time,avg(verbrauch) as Watt from channel_007 where MONTH (time) = '01' AND YEAR(time) = '2014' group by ((60/10) * HOUR(time)+ FLOOR( MINUTE(time) / 10 )), MONTH(time), DAY(time) ;我怎样才能加入这两个查询?谢谢
猜你喜欢
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多