SQL行状态更改之间的时间

时间:2016-01-19 00:45:32

标签: sql sqlite

我有一个sqlite3表,记录我的加热系统的状态和每30秒一次。该表看起来像这样

TABLE CLIMATESYSTEM (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    Timestamp INT,
    FAN INT,
    SYSTEM INT
);

timestamp是自python

中的epoch((int)time.time)以来的秒数

表中的几行看起来像这样

5577|1452049280|1|1
5578|1452049339|1|1
5579|1452049399|1|1
5580|1452049459|1|1
5581|1452049520|0|0
5582|1452049580|0|0
5583|1452049644|1|1
5584|1452049700|1|1
5585|1452049760|1|1
5586|1452049820|0|0

我要做的是计算状态转换从开启(1)到关闭(0)与下一次从关闭转换为开启之间的秒数。

示例计算#5577和#5581之间的秒数 - >添加到TIME_SYS_ON

示例计算#5581和#5583之间的秒数 - >添加到TIME_SYS_OFF

我打算做的是测量我的加热系统运行的24小时内的总时间

关于起点的任何想法?

由于

1 个答案:

答案 0 :(得分:0)

首先,查找每一行的下一个时间戳:

SELECT Timestamp,
       (SELECT MIN(Timestamp)
        FROM ClimateSystem AS CS2
        WHERE CS2.Timestamp > ClimateSystem.Timestamp
       ) AS NextTimestamp,
       System
FROM ClimateSystem;

然后用它来计算每个区间的长度:

SELECT NextTimestamp - Timestamp,
       System
FROM (SELECT Timestamp,
             (SELECT MIN(Timestamp)
              FROM ClimateSystem AS CS2
              WHERE CS2.Timestamp > ClimateSystem.Timestamp
             ) AS NextTimestamp,
             System
      FROM ClimateSystem);

然后根据需要添加过滤器:

SELECT SUM(NextTimestamp - Timestamp),
       System
FROM (SELECT Timestamp,
             (SELECT MIN(Timestamp)
              FROM ClimateSystem AS CS2
              WHERE CS2.Timestamp > ClimateSystem.Timestamp
             ) AS NextTimestamp,
             System
      FROM ClimateSystem)
WHERE Timestamp BETWEEN :StartOfDay AND :EndOfDay
GROUP BY System;