SQLAlchemy:pandas sql_query中的聚合查询

时间:2016-12-27 15:26:03

标签: python pandas sqlalchemy

模型:League有许多Season有许多Round有许多GameTeam有两对一的关系。

每个游戏的总目标都保存在SQLAlchemy column_property中。

我无法弄清楚如何将正确的查询传递给pandas read_sql。我正在尝试的所有变化都不起作用,包括:

pandoc = pd.read_sql(Match.query.join(Round).
                 join(Season).
                 join(League).filter(Match.round).filter(Round.season).filter(Season.league)
                 .statement, db.session.bind)

其中输出如下:(我已经放弃了几轮)

  total_goals   round_id  home_goals  away_goals finished
0             1.0   sxxx-0         1.0         0.0     True
1             0.0   sxxx-0         0.0         0.0     True
2             2.0   sxxx-0         2.0         0.0     True
3             3.0   sxxx-0         3.0         0.0     True

我想要的理想是:

League    total_goals
league.name total_goals (across all seasons)

试图从League向下遍历似乎更符合逻辑,但这也没有用。

1 个答案:

答案 0 :(得分:1)

这很有效,但我不确定它是否是“最佳”方式:

pandoc = pd.read_sql(League.query.
                     join(Season).
                     join(Round).
                     join(Match).with_entities(func.sum(Match.total_goals).label('total_goals'), League.name).
                     group_by(League.name).
                     statement, db.session.bind)
相关问题