【问题标题】:Sqlalchemy ORM group by twice / subquery in a single statementSqlalchemy ORM 在单个语句中按两次/子查询分组
【发布时间】:2021-05-09 13:49:14
【问题描述】:

我尝试将以下 SQL 语句转换为 sqlalchemy ORM 查询:

select name, max(pnl) from 
    (
       select name, filedate, sum(pnl) as pnl from portfolio 
       where filedate>="2020-01-01" 
       group by filedate, name
    ) maxg 
group by name

我似乎无法将其转换为 ORM 查询,这是我迄今为止尝试过的,构建内部子查询,但我似乎无法为外部查询构建 ORM 查询。有没有办法为内部子查询设置别名,以便我可以继续引用这些字段?

from sqlalchemy import func

session.query(
    Entity.name, Entity.filedate, func.sum(Entity.pnl).label("pnl"))
       .filter(Entity.filedate >= datetime.date(2020,1,1))
       .group_by(Entity.filedate, Entity.name)
)

【问题讨论】:

    标签: python sqlalchemy orm


    【解决方案1】:

    如果有人有同样的问题,这为我解决了这个问题,尽管实现起来很丑陋。可以使用subquery() 创建子查询,并通过subquery.c.{columnname} 访问列

    # Subquery
    sq = session.query(
        Entity.name, Entity.filedate, func.sum(Entity.pnl).label("pnl"))
           .filter(Entity.filedate >= datetime.date(2020,1,1))
           .group_by(Entity.filedate, Entity.name)
    ).subquery()
    
    session.query(sq.c.name, func.max(sq.c.pnl))
        .group_by(sq.c.name).all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2016-08-25
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多