Sqlite 返回最新值与 24 小时前值之间的行差异

Posted

技术标签:

【中文标题】Sqlite 返回最新值与 24 小时前值之间的行差异【英文标题】:Sqlite return row difference between latest value and value 24 hours earlier 【发布时间】:2020-05-15 10:01:44 【问题描述】:

这里是 Sqlite 菜鸟。 我有一个 SQLite 时间序列数据库,每四分钟更新一次,我想报告最近数据点与(大约)24 小时前的数据点之间的行值差异。 如果我运行

SELECT entity_id, state, last_changed
FROM "states" where entity_id = "sensor.nodered_46ce6408_d3dd5c" and last_changed > "1002020-05-14 18:12:28.008172"

我明白了

entity_id   state   last_changed
sensor.nodered_46ce6408_d3dd5c  6940.38     2020-05-04 18:14:35.969094
sensor.nodered_46ce6408_d3dd5c  6940.4      2020-05-04 18:18:45.913404
sensor.nodered_46ce6408_d3dd5c  6940.42     2020-05-04 18:22:55.892357 

但使用以下作为第一步,我什至没有得到最后两个值之间差异的结果。

SELECT entity_id, state, last_changed,
    (SELECT A.state - B.state
        FROM states as B
        WHERE B.entity_id = A.entity_id AND
            B.last_changed = (SELECT MAX(last_changed) FROM states C WHERE C.last_changed > A.last_changed AND C.entity_id = A.entity_id)) AS difference
FROM states as A 

我不需要将差异结果写入表中,我只需要每隔几个小时运行一次查询的结果。

有解决这个问题的线索吗? TIA。

编辑

我已经改进了我的查询,但还没有。我得到一个接近“SELECT”:语法错误

SELECT state
    FROM states
    SELECT (A.state - B.state)
    WHERE B.(entity_id = "sensor.nodered_46ce6408_d3dd5c" AND last_changed >= datetime('now', 'localtime','-24 hours') order by last_changed limit 1) AND A.(entity_id = "sensor.nodered_46ce6408_d3dd5c"
    AND last_changed <=  datetime('now', 'localtime') order by last_changed desc limit 1)

【问题讨论】:

【参考方案1】:

有效的答案是:

SELECT b.entity_id, 
       b.state, 
       b.last_changed, 
       ( b.state - (SELECT a.state 
                    FROM   states a 
                    WHERE  a.entity_id = "sensor.nodered_46ce6408_d3dd5c" 
                           AND a.last_changed >= Datetime('now', 'localtime', 
                                                 '-24 hours' 
                                                 ) 
                    ORDER  BY a.last_changed 
                    LIMIT  1) ) AS difference 
FROM   states b 
WHERE  b.entity_id = "sensor.nodered_46ce6408_d3dd5c" 
       AND b.last_changed <= Datetime('now', 'localtime') 
ORDER  BY b.last_changed DESC 
LIMIT  1

感谢@sukitha

【讨论】:

以上是关于Sqlite 返回最新值与 24 小时前值之间的行差异的主要内容,如果未能解决你的问题,请参考以下文章

Sqlite 返回值与数据库不同

使用java在sqlite中选择两个日期之间的行

SQLite组日期时间以168小时(7天)为单位返回NULL

从 SQLite 中的所有行中减去平均值

Sum Time SQlite PHP 超过 24 小时

查询以选择每小时最新的员工条目