【问题标题】:Convert SQL statement to SQLAlchemy将 SQL 语句转换为 SQLAlchemy
【发布时间】:2022-09-27 15:29:25
【问题描述】:

我需要将此 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 
  • 请提供您尝试过的方法以及遇到问题的地方。
  • 我在 python 快速 API SELECT 区域中使用此代码,count(fall_status) FROM events WHERE events.timestamp BETWEEN 1663460366 AND 1663546766 AND events.fall_status = 1 GROUP by zone <==== 这是代码 sn-p 但我想要 events = db.query(Events).filter(Events.timestamp.between(to_date,from_date)).all() 这个 python 格式

标签: sql sqlite sqlalchemy


【解决方案1】:

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

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)

【讨论】:

  • events = db.query(Events).filter(Events.timestamp.between(to_date,from_date)).all() 我需要这样
【解决方案2】:
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()

func.count

【讨论】:

  • q = db.query(Events.zone, func.count(Events.fall_status)).filter(Events.fall_status == 1).filter(Events.timestamp.between(from_date,to_date)).group_by(Events.zone) 。全部()
  • @DeebaMathan,谢谢,更新了答案。
猜你喜欢
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2011-10-18
  • 1970-01-01
  • 2013-02-15
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多