'How to use sqlalchemy's func.sum with group_by

I need to get the func.sum in sqlalchemy to get the total points in different percentages. I have a table with the users and another table with the categories the users can be in. The users can be in one or multiple categories. We will have a category ranking AND an Overall ranking. The overall ranking will have players in category A getting 100% of the points. Players in category B getting 20% of the points. There is a table called Points where we keep track of every single entry of points for each user and category. To get the ranking per category we just func.sum on the total_points and group by user_id and category id. Now, to get the overall ranking we need to get the func.sum with 100% of the points from category A + 20% of the total_points from category B. It's something like a subquery inside the func.sum.

This is what I have to get the total points per category:

subquery = db.session.query(User.firstname, User.lastname, PlayerTournamentPoint.user_id, PlayerTournamentPoint.category_id, PlayerTournamentPoint.total_points, func.rank().over(order_by=PlayerTournamentPoint.total_points.desc(), partition_by=PlayerTournamentPoint.user_id).label('rank')).join(Tournament, Tournament.id == PlayerTournamentPoint.tournament_id).filter(User.id == PlayerTournamentPoint.user_id).subquery()    

db.session.query(subquery, func.sum(subquery.c.total_points), func.count(subquery.c.user_id)).filter(subquery.c.rank <=7).order_by(func.sum(subquery.c.total_points).desc()).group_by(subquery.c.user_id, subquery.c.category_id).subquery()

How can we accomplish that?

===== EDIT =====

Here is an example of what I want to accomplish

USER A - CATEGORY A - 100 Points
USER B - CATEGORY A - 50 points
USER A - CATEGORY B - 100 Points

Category A ranking:

User A - 100 points
User B - 50 points

Category B ranking:

User A - 100 points

Overall ranking:

User A - 120 points (100 from category A and 20 from category B. i.e 20% of 100 points)
User B - 50 points


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source