sql - 在SQL中使用计数器值计算行之间的差异

标签 sql sqlite

我在表T1中更新了一些计数器值

id, unix_time_stamp, counter1, counter10
1 , 1333435800     , 55      , 80


然后我得到表T2,我在其中复制这些值

id, unix_time_stamp, counter1, counter10, value1, value10
1 , 1333435800     , 55      , 80       , 0     , 0
2 , 1333435801     , 60      , 87       , 5     , 7
3 , 1333435802     , 70      , 90       , 10    , 3
3 , 1333435804     , 80      , 100      , 5     , 5


这是通过一些触发功能完成的

INSERT INTO T2 (unix_time_stamp, counter1, counter10) SELECT unix_time_stamp, counter1, counter10 FROM T1 WHERE id=1


我想要的是将value1,value10计算为

(current_counter1 - last_counter1)/(current_time - last_time)


并将它们放在此插入中

例如带有时间戳1333435804的值1将是

value1=(80-70)/(1333435804-1333435802) = 5


也就是说

insert into t2
(unix_time_stamp, counter1, counter10, value1)
SELECT unix_time_stamp, counter1, counter10, 
(counter1 - (select counter1 from T1 order by unix_time_stamp DESC LIMIT 1)/
(unix_time_stamp - (select unix_time_stamp from T1 order by unix_time_stamp DESC LIMIT 1)
FROM T1 WHERE id=1


但是我想要一个短一点的版本,因为我有10个计数器:)

整体情况有点复杂,我有一些理由不在SQL之外执行此操作

我正在使用sqlite

这对我来说太复杂了:)
请帮忙。

最佳答案

我想以下查询将计算您的insert子句所需的所有数据:

SELECT 1e0 * (cur.counter1 - prv.counter1)/(cur.unix_time_stamp - prv.unix_time_stamp)   AS [value1]
, 1e0 * (cur.counter10 - prv.counter10)/(cur.unix_time_stamp - prv.unix_time_stamp)      AS [value10]
, cur.counter1 AS [cur_counter1], cur.counter10 AS [cur_counter10], cur.unix_time_stamp AS [cur_time]
, prv.counter1 AS [prv_counter1], prv.counter10 AS [prv_counter10], prv.unix_time_stamp AS [prv_time]
FROM T1 cur, T1 prv
WHERE cur.counter1 = (SELECT MAX(aux_0.counter1) FROM T1 aux_0)
AND prv.counter1 = (SELECT MAX(aux_1.counter1) FROM T1 aux_1 WHERE aux_1.counter1 < cur.counter1);

关于sql - 在SQL中使用计数器值计算行之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334147/

相关文章:

python - 通过 pandas to_sql 命令检查数据库插入结果 - Flask

Sqlite:基于非主键字段创建具有重复行的表

android - 如何使用 context.getContentResolver() 通过 CASE WHEN 语句执行更新

java - Android SQLite :could not execute method onclick

java - 使用 tsVector 在 NativeQuery 中设置参数

sql - 逗号分隔结果多列sql server

MySQL:根据两个标准对多列中的整数值进行计数和总和

sql - 通过选择查询将一列拆分为两列

c# - 如何循环遍历数据集(来自存储过程)并检查每行的单个字段

java - 如果字符串包含双引号,则搜索 SQLite 表