sqlite 将SQL语句转换为SQLAlChemy

stszievb  于 2022-11-15  发布在  SQLite
关注(0)|答案(2)|浏览(150)

我需要将此SQL语句转换为SQLAlChemy ORM查询:

SELECT zone, count(fall_status)
FROM events
WHERE events.timestamp BETWEEN 1663460366 AND 1663546766
AND events.fall_status = 1 
GROUP by zone
7fyelxc5

7fyelxc51#

首先,您需要创建一个引擎:

from sqlalchemy import create_engine
engine = engine = create_engine('sqlite:///...')

然后你就可以使用

from sqlalchemy.sql import text
with engine.connect() as conn:
    statement = text("SELECT zone, count(fall_status) from events WHERE events.timestamp BETWEEN 1663460366 AND 1663546766 AND events.fall_status = 1 GROUP by zone")
conn.execute(statement)
c8ib6hqw

c8ib6hqw2#

q = (
    db.query(
        Events.zone, 
        func.count(Events.fall_status),
    )
    .filter(Events.fall_status == 1)
    .filter(Events.timestamp.between(to_date,from_date))
    .group_by(Events.zone)
).all()

请参阅函数.计数

相关问题