SQLAlchemy:sql\u查询中的聚合查询

2024-04-29 14:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

模型:League有许多Season有许多Round有许多GameTeam有两个一对一的关系。你知道吗

每场比赛的总进球数保存在SQLAlchemycolumn_property中。你知道吗

我看不出如何将正确的查询传递给pandasread_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向下遍历似乎更符合逻辑,但也没有奏效。你知道吗


Tags: 模型gametruesqlmatchfilterseasontotal
1条回答
网友
1楼 · 发布于 2024-04-29 14:25:28

这很管用,但我不确定这是不是最好的方法:

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)

相关问题 更多 >