繁体   English   中英

将 SQL 语句转换为 SQLAlchemy

[英]Convert SQL statement to SQLAlchemy

我需要将此 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 

首先你需要创建一个引擎:

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)
q = (
    db.query(
        Events.zone, 
        func.count(Events.fall_status),
    )
    .filter(Events.fall_status == 1)
    .filter(Events.timestamp.between(to_date,from_date))
).all()

func.count

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM