用于比较满足时间戳条件

时间:2018-04-25 13:18:58

标签: sql sql-server timestamp

我有以下格式的数据。

Column1     Column2     Column3         TimeStamp
   10           20         30       2017-04-25 14:15:00.000
   12           30         40       2017-04-25 14:15:15.000
   55           54         89       2017-04-25 14:15:30.000
   66           78         11       2017-04-25 14:15:45.000
   12           30         40       2017-04-25 14:16:00.000
   55           54         89       2017-04-25 14:16:15.000
   66           78         11       2017-04-25 14:16:30.000

时间戳的格式为

  

yyyy-mm-dd hh:mm:ss

每15秒记录一次数据。因此,任何连续两行的时间戳之间的差异应为15秒。我有兴趣查询时差为例如20秒的行 在TimeStamps 2017-04-25 14:15:00和2017-04-25 14:15:30之间。

我开始使用以下代码,并且它将永远完成查询。

SELECT
  *
FROM
  dbo.Temp2 AS t1
WHERE
  EXISTS
  (
    SELECT
      *
    FROM
      dbo.Temp2 AS t2
    WHERE
      t2.TimeStamp - t1.TimeStamp = 20      
  )
  ;

我正在使用MS SQL Server 2017。

任何建议,想法都会非常有用。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用create table #MyTable (C1 int, C2 int, C3 int, TimeStamps datetime) insert into #MyTable values (10,20,30,'2017-04-25 14:15:00.000'), (12,30,40,'2017-04-25 14:15:15.000'), (55,54,89,'2017-04-25 14:15:30.000'), (66,78,11,'2017-04-25 14:15:45.000'), --this row will also be returned (12,30,40,'2017-04-25 14:16:15.000'), --changed minutes here. This is the only row > 15 second difference than the previous, ordered by TimeStamps (55,54,89,'2017-04-25 14:16:30.000'), (66,78,11,'2017-04-25 14:16:45.000') ;with cte as( select * ,KeepMe = case when datediff(second,TimeStamps,lead(TimeStamps) over(order by TimeStamps)) > 20 or datediff(second,TimeStamps,lag(TimeStamps) over(order by TimeStamps)) < -20 then 1 else 0 end from #MyTable) select C1 ,C2 ,C3 ,TimeStamps from cte where KeepMe = 1 drop table #MyTable willSet。我还将您的样本数据更改为实际上有超过15秒的间隙。这将返回发生间隙两个行。在这种情况下,它是下面评论的两个。

didSet

答案 1 :(得分:1)

领先/滞后分析功能在这里可能会有所帮助:

WITH cte AS (
    SELECT *,
        DATEDIFF(s, TimeStamp, LEAD(TimeStamp, 1) OVER (ORDER BY TimeStamp)) AS diff
    FROM Temp2
    WHERE TimeStamp BETWEEN '2017-04-25 14:15:00' AND '2017-04-25 14:30:00'
)

SELECT *
FROM cte
WHERE diff >= 20;

Demo

在上面的演示中,我不得不稍微对您的样本数据进行处理,以便返回任何内容,因为您的时间戳范围实际上没有值,使得下一个前导值相隔20秒。