[英]problem with lag function in python sqlite3
有以下代码在 sqlite3 中创建表
import sqlite3 as sq
con = sq.connect('test2.db')
q = """
create table if not exists test (ip TEXT, time INTEGER, value INTEGER);
insert into test (ip, time, value) values("192.168.1.1", 1607190826, 3010);
insert into test (ip, time, value) values("192.168.1.1", 1607190827, 3012);
insert into test (ip, time, value) values("192.168.1.1", 1607190828, 3019);
insert into test (ip, time, value) values("192.168.1.2", 1607190829, 510);
insert into test (ip, time, value) values("192.168.1.2", 1607190829, 515);
insert into test (ip, time, value) values("192.168.1.2", 1607190829, 530);
"""
con.executescript(q)
con.commit()
我像这样在 sqlite 中使用滞后 function
qw = """SELECT ip, lag(value, 1, 0) OVER (ORDER BY ip) val2 from test"""
f = con.execute(qw)
for i in f:
print(i)
但我收到以下错误代码。
OperationalError: near "(": syntax error
更新
它适用于 python 3.7。
我仍然对 python 3.6 有问题
在 SQLite 的 3.25 之前版本中,不支持 window 函数,您可以使用相关子查询模拟lag()
。
从您的示例数据中,我怀疑您想要按time
排序的相同ip
的先前value
- 这不是您的代码所做的。 window function 版本将是:
select ip, lag(value, 1, 0) over(partition by ip order by time) as val2
from test
等效的子查询解决方案如下:
select ip,
coalesce(
(
select value
from test t1
where t1.ip = t.ip and t1.time < t.time
order by t1.time desc limit 1
),
0
) as val2
from test t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.