SQLite 选择计数 10 小时前的记录

标签 sqlite select

我有这个数据库

Table [Ticks]
    Fields: 2
        [Value]: INT
        [Time]: DATETIME
    Indexes: 1
        [TicksIdx]
            [Time] 
            [Value] 
    Triggers: 0
    Table constraints: 
        Primary Key: 
            Fields: 
            On Conflict: 
        Foreign Keys: 0
        Unique constraints: 0
        Check constraints: 0
Table [Ticks] end

我想计算从 10 小时前到现在的 value=-1 和 Time < (Now-10 hours) 的所有记录

我有这个查询,总是返回 0
select count(*) from Ticks where Value=-1 and
time>=datetime('now', '-10 hours')

如果我将查询更改为此,它将返回所有记录
select count(*) from Ticks where Value=-1 and
time<datetime('now', '-10 hours')

我有时间值最近超过 10 小时的记录

最佳答案

解释

您的问题将是由于存储在时间列中的值不是可识别的格式,也很复杂,因为没有比较喜欢。

SQLite 识别的格式可以在这里找到 SQL As Understood By SQLite - Date And Time Functions - Time Strings .

例如 YYYY-MM-DD HH:MM:SS (例如 2018-12-09 12:40:01)就是这样一种公认的格式。

您查询的是(假设来自 c# 的 9/12/2018 12:40:01 AM 并且运行时相同)说:-

  • 2018 年 9 月 12 日上午 12:40:01 >= 2018-12-09 12:40:01

  • 由于这些值是非数字的,因此会进行逐个字符的比较,因此使用这些时间 9 大于 2(当然,如果它是 09/12 ......那么就不是)。

    如果基础数据采用可识别的格式,则确保类似比较的正确方法是确保双方比较 dimetime 的实际情况,因此 SQL 应该是:-
    SELECT count(*) FROM Ticks WHERE Value=-1 AND datetime(time) >= datetime('now', '-10 hours')
    
  • 注意 datetime(time) 仅当时间列中的日期是另一种可识别的格式而不是示例格式时才需要。

  • -注意您可能需要合并本地时间来调整时间,例如datetime(time) >= datetime('now','localtime', '-10 hours')
  • 根据
  • The "localtime" modifier (12) assumes the time string to its left is in Universal Coordinated Time (UTC) and adjusts the time string so that it displays localtime. If "localtime" follows a time that is not UTC, then the behavior is undefined. The "utc" modifier is the opposite of "localtime". "utc" assumes that the string to its left is in the local timezone and adjusts that string to be in UTC. If the prior string is not in localtime, then the result of "utc" is undefined.


  • 修复

    要解决此问题,您需要
  • 根据时间列中值的格式,对时间列进行复杂的重新格式化,以进行比较(不推荐)
  • 或确保该值以 SQlite 可识别的格式存储。

  • 如果时间是插入刻度行的当前时间,那么您可以使用 time DATETIME DEFAULT CURRENT_TIMESTAMP作为 的定义时间列而不提供 的值时间插入行时的列。

    否则,您应该在存储值之前将值的格式更改为可识别的格式。

    关于SQLite 选择计数 10 小时前的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686708/

    相关文章:

    mysql - 从多个表中获取多个数据

    MySQL:根据第二个表中的真假比选择行

    javascript - 如何从 Html Select 标签中隐藏第一项

    sql - sql-选择与其他行中的值进行比较的行

    SQlite 查询更新列并替换值

    android - 为 Android 应用程序在线托管数据库

    mysql - 为什么 mysql 中的这个查询适用于表但不适用于该表的 View ?

    sqlite - Flutter解码一列SQLite查询结果

    sqlite - Monotouch - sqlite 和希伯来字符

    ruby-on-rails - 在 Rails collection_select 中使用短日期时间