I'm building a data dashboard for a project where players field a certain position within a game. Players can also field multiple positions in a single game. I want a query that will return:
- Each player in the Player table
- The number of games that player has appeared in, regardless of whether they appeared in multiple positions in that game. (i.e. if Fred appears at 3 positions each in 2 games, the query should return 2 not 6)
- The winning percentage of games in which that player appeared. (i.e. if John appears in 20 games and 11 of them have `outcome="Win", the query should return 0.55)
For example, an output like:
[("John", 20, 0.55), ("Alejandro", 15, 0.75), ("Fred", 13, 0.5),...]
My database tables look like this:
# I'm using sqlalchemy and Flask_SQLAlchemyfrom my_flask_app import dbfrom sqlalchemy.ext.associationproxy import association_proxyclass Game(db.Model):""" Represents a game. Each game can have several players at different positions. A single player can appear in a game multiple times at different positions (i.e. have multiple GameToPlayerPosition associations).""" id = db.Column(db.Integer, primary_key=True) # "Win" or "Loss" outcome = db.Column(db.String(10), nullable=False) ... # Other fields positions = db.relationship("GameToPlayerPosition", back_populates="game", cascade="all, delete" ) players = association_proxy("positions","player", creator=lambda player, position: GameToPlayerPosition(player=player, position=position), )class GameToPlayerPosition(db.Model):""" Association table connecting Game to Player. Adds some additional information, namely the `position` column shown here.""" game_id = db.Column(db.ForeignKey("game.id"), primary_key=True) player_id = db.Column(db.ForeignKey(f"player.id"), primary_key=True) position = db.Column(db.String(10), nullable=False) ... # Other fields game = db.relationship("Game", back_populates="positions") player = db.relationship("Player", back_populates="game_positions")class Player(db.Model):"""Players in a game.""" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), nullable=False, unique=True) ... # Other fields game_positions = db.relationship("GameToPlayerPosition", back_populates="player", cascade="all, delete" ) games = association_proxy("game_positions", "game")