Sqlalchemy 由多个聚集体组成的炼金术组

Sqlalchemy 由多个聚集体组成的炼金术组,sqlalchemy,Sqlalchemy,我想在Flask SQLAlchemy中编写一个具有两级group by的查询,它相当于下面的SQL代码 select right_team_id team_id ,sum(score)-sum(deductions) score from ( select left_team_id, right_team_id ,1.0*sum(case when right_win then 1 else 0 end)/count(*) score ,1.0*sum(right_deductio

我想在Flask SQLAlchemy中编写一个具有两级group by的查询,它相当于下面的SQL代码

select right_team_id team_id
,sum(score)-sum(deductions) score from (
  select left_team_id, right_team_id
  ,1.0*sum(case when right_win then 1 else 0 end)/count(*) score
  ,1.0*sum(right_deductions)/2 deductions
  from races
  group by left_team_id, right_team_id ) A
group by right_team_id
对于第一组,我从以下内容开始

query = Races.query.group_by(Races.left_team_id, Races.right_team_id)
.add_columns(func.sum(Races.left_deductions).label('deductions')
,func.sum(case([(Races.left_win, 1)], else_ = 0)).label('wins')
,func.count().label('races'))
但是查询中的每个记录都是以下内容
(,0,0,1)
。如何运行另一个group by查询,包括末尾的聚合列


感谢没有db,或者底层架构是什么,这很难验证。另外,原始sql查询和sqlalchemy查询有很大不同。但我认为使用子查询来实现这一点会很好

subq = db.session.query(Races.right_team_id.label('right_team_id'),
             (func.sum(case([(Races.right_win, 1)], else_ = 0))/func.count(Races.id)).label('score'),
             (func.sum(right_deductions)/2).label('deductions')).group_by(Races.left_team_id, Races.right_team_id).subquery()

q = db.session.query(Races.right_team_id, func.sum(subq.c.score)-func.sum(subq.c.deductions)).\
join(subq, subq.c.right_team_id==Races.right_team_id).group_by(Races.right_team_id)