按时间戳和值的sqlite查询

ewm0tg9j  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(473)

我有一个 Sqlite 包含以下行的表: id :int pk自动递增 timestamp :int值不为null。db插入的时间戳 value :int值不为null。可能值[0-4]。
我想查询数据库以获得在给定时间戳之前60秒内包含的寄存器的数据库上的所有值是否都相同 value . 例如:

id | timestamp  | value
1  | 1594575090 |   1
2  | 1594575097 |   1
3  | 1594575100 |   1
4  | 1594575141 |   2
5  | 1594575145 |   2
6  | 1594575055 |   3
7  | 1594575060 |   4

在本例中,如果我对寄存器前60秒中包含的寄存器进行了预期的查询 3 (包括登记册) 3 ),它应该查询寄存器的值 [1,2, 3] 都是一样的,应该 return 1 .
另一方面,如果这个查询是用register完成的 7 ,它会比较 value 寄存器数量 [4,5,6,7] 它应该 return 0 ,因为这三个值不相同。
你猜我该如何执行这个查询?

s2j5cfk0

s2j5cfk01#

我想你想要这个:

select count(distinct value) = 1 result
from tablename
where id <= ? 
and timestamp - (select timestamp from tablename where id = ?) <= 60;

更换 ? 占位符,其id为您想要的结果。
可能您希望时间戳差值的绝对值小于60,因此如果是这种情况,请更改为:

and abs(timestamp - (select timestamp from tablename where id = ?)) <= 60;

请看演示。

b1uwtaje

b1uwtaje2#

嗯。我认为你所描述的逻辑是:

select ( min(value) = max(value) ) as all_same
from t cross join
     (select t.*
      from t
      where t.id = ?
     ) tt
where t.timestamp < tt.timestamp and
      t.timestamp >= tt.timestamp - 60

相关问题