Flask-SQLAlchemy Group by Multiple Aggregates

时间:2016-04-05 21:16:14

标签: sqlalchemy

我想在Flask-SQLAlchemy中编写一个包含两个级别的查询,这相当于以下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'))

但查询中的每条记录都是以下(<flaskapp.races.models.Races object at 0x107c5f358>, 0, 0, 1)。如何通过查询运行另一个组,包括最后的聚合列?

由于

1 个答案:

答案 0 :(得分:2)

没有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)