简体   繁体   中英

Convert SQL statement to SQLAlchemy

I need to convert this SQL statement to an SQLAlchemy ORM query:

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

First you need to create an engine:

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

Then you can use

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()

see func.count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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