简体   繁体   English

SQLAlchemy 组合查询

[英]SQLAlchemy combine query

I need to execute this SQL:我需要执行这个 SQL:

select 
    `year`, 
    `month`, 
    sum(diff) 
from 
    (select 
         `year`, `month`, 
         `readings` - LAG(`readings`) over (order by `year`) as diff 
     from table1) as summary 
group by 
    `year`, `month`

But I need to do it in SQLAlchemy.但我需要在 SQLAlchemy 中进行。

So far I figured out 2 subqueries:到目前为止,我发现了 2 个子查询:

q1 = db.session.query(Table1.year, Table1.month, (Table1.readings - func.lag(Table1.readings).over(order_by=Table1.year)).label('diff'))

result = db.session.query(Table1.year, Table1.month, sum('diff')).group_by(Table1.year, Table1.month)

But I can't combine them together但我不能将它们结合在一起

Just turn q1 into a subquery() and select from it.只需将q1转换为subquery()和 select 即可。

q1 = db.session.query(
        Table1.year,
        Table1.month,
        (Table1.readings - func.lag(Table1.readings).over(order_by=Table1.year)).label('diff')).\
    subquery()

result = db.session.query(q1.c.year, q1.c.month, sum(q1.c.diff)).group_by(q1.c.year, q1.c.month)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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