Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert rank and partition query to SqlAlchemy

I would like to convert the following query to SqlAlchemy, but the documentation isn't very helpful:

select * from (
select *, 
RANK() OVER (PARTITION BY id ORDER BY date desc) AS RNK 
from table1
) d
where RNK = 1

Any suggestions?

like image 818
user1742188 Avatar asked Nov 16 '16 14:11

user1742188


1 Answers

use over expression

from sqlalchemy import func

subquery = db.session.query(
    table1,
    func.rank().over(
        order_by=table1.c.date.desc(),
        partition_by=table1.c.id
    ).label('rnk')
).subquery()

query = db.session.query(subquery).filter(
    subquery.c.rnk==1
)
like image 77
r-m-n Avatar answered Oct 19 '22 12:10

r-m-n