我希望将以下sql语句转换为sql alchemy
select c1.id, c1.repository, c1.branch, c1.failed_step, c1.stop_time
from completed_builds as c1
where c1.stop_time = (
select max(c2.stop_time)
from completed_builds as c2
where c1.branch = c2.branch
and c1.repository = c2.repository
)
and c1.repository in ('flex', 'mob', 'tv')
and c1.branch in ('stage', 'int')
order by c1.repository, c1.branch
这将输出具有最高stop_time值的唯一分支+存储库对。
非常感谢!
答案 0 :(得分:0)
使用子查询添加过滤器。
subq = (db.query(CompletedBuilds.id,
func.max(CompletedBuilds.stop_time).label(‘max_stop_time’)
CompletedBuilds.branch,
CompletedBuilds.repository)
.subquery())
q = (db.query(CompletedBuilds)
.join(subq, subq.id == CompletedBuilds.id)
.filter( subq.branch == CompletedBuilds.branch,
subq.repository == CompletedBuilds.repository,
CompletedBuilds.repository.in_(‘flex’, ‘mob’, ‘tv’),
CompletedBuilds.branch.in_(‘stage’, ‘int’))
.order_by(CompletedBuilds.repository, CompletedBuilds.branch))