【问题标题】:Sqlite query by timestamp and valueSqlite 按时间戳和值查询
【发布时间】:2020-07-12 17:39:49
【问题描述】:

我有一个 Sqlite 表,其中包含以下行:

  • id: int PK 自动增量
  • timestamp:int 值非空。数据库插入的时间戳
  • value:int 值 NOT 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

在这种情况下,如果我对寄存器3(包括寄存器3)之前60秒包含的寄存器进行了预期的查询,它应该查询寄存器[1,2, 3]的值是否为一样,应该是return 1

另一方面,如果这个查询是用寄存器7 完成的,它会比较value 的寄存器[4,5,6,7] 和它应该return 0,因为这个值对于它们三个是不一样的。

你猜我该如何执行这个查询?

【问题讨论】:

  • 时间戳不是按id升序排列的吗?

标签: sql sqlite timestamp sql-timestamp


【解决方案1】:

我认为你想要这个:

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;

请参阅demo

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2023-03-11
      • 2022-01-10
      • 1970-01-01
      • 2017-09-10
      • 2021-01-11
      • 2020-10-22
      • 2020-12-26
      • 2021-05-30
      相关资源
      最近更新 更多