检测 SQLite 中日期之间的间隙

问题描述 投票:0回答:2

我有一个具有以下结构的 SQLite 表:

正如您所看到的,

sampleDate
列每1分钟就有一个新行,但有时该过程会停止并且存在“时间间隙”,如下划线示例所示。我需要通过
SQL
查询找到这些差距,因为这个表很大。

可能的预期结果输出可能是:

2023-03-20 12:56:27
2023-03-29 10:46:46

这可能表示这两个日期之间存在差距。

sql sqlite gaps-and-islands
2个回答
0
投票

您可以使用

LEAD()
函数检索下一个日期,然后计算差异以检索间隙:

with cte as (
  select *, 
          lead(sampleDate, 1, sampleDate) over (order by sampleDate) as nextDate,
          CAST(strftime('%M', lead(sampleDate, 1, sampleDate) over (order by sampleDate)) as integer) 
          - CAST(strftime('%M', sampleDate) as integer) as diff
  from mytable
)
select sampleDate, nextDate
from cte
where diff > 1

0
投票

或者您可以使用左反连接来获取没有下一分钟记录的行吗?下面提供的示例 -

with cte as (
  select 4556 id, datetime('2023-03-20 12:54:27') sampleDate
  union ALL
  select 4557 id, datetime('2023-03-20 12:55:27') sampleDate
  union ALL
  select 4558 id, datetime('2023-03-20 12:56:27') sampleDate
  union ALL
  select 4559 id, datetime('2023-03-29 10:46:46') sampleDate
  union ALL
  select 4560 id, datetime('2023-10-06 10:52:47') sampleDate
  union ALL
  select 4561 id, datetime('2023-10-06 10:53:47') sampleDate
 )
 select a.* from cte a 
 left join cte b ON  b.sampledate = datetime(a.sampleDate,'+1 minutes') -- if wanted the gap to be exact one minutes
            --  ON b.sampledate between datetime(a.sampleDate,'+1 seconds')  and datetime(a.sampleDate,'+1 minutes')  -- if you wanted the gap to be anywhere under a minute
 where b.id is NULL
© www.soinside.com 2019 - 2024. All rights reserved.