I have the following SQL statement that I'm trying to convert into a sqlalchemy ORM query:
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
I can't seem to convert this into an ORM query, this is what I have tried so far, building the inner subquery, but I can't seem to construct the ORM query for the outer query. Is there a way to alias the inner subquery so that I can continue to reference the fields?
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)
)