Serversphere
02-08-2008, 06:43 PM
This one has me really stumped. I am trying to grab winning percentages for players on a sports based website and I just can't get my head around the proper query. I have two tables:
Table 1: players
player_id
firstname
lastname
Table 2: game_data
id
player_id
game_id
season
position
I want to grab a player's id, name, games played, games won and winning percentage, which I know to be wins divided by total games played times 100. Total games played would be a count(*) and wins would be a count(*) where position is equal to 1. This will be done in a PHP function, so I also need the query to take into account season. There are other tables holding game and season information, but they are not relevent to this query.
So I've tried this query to grab season 1 winning percentages:
SELECT p.player_id,
CONCAT(p.firstname,' ',p.lastname) AS player_name,
COUNT(*) AS games_played,
(SELECT COUNT(*) FROM game_data WHERE player_id=p.player_id AND position=1 AND season=1) AS games_won,
(games_won/games_played)*100 AS winning_percentage
FROM game_data AS g
WHERE season=1
INNER JOIN players AS p
ON p.player_id=g.player_id
GROUP BY p.player_id
ORDER BY winning_percentage DESC
But it doesn't work. I get an error that games_won is an unknown field on the line that calculates the win percentage, so I am assuming I have to calculate this on the fly rather than post query. Any thoughts?
Table 1: players
player_id
firstname
lastname
Table 2: game_data
id
player_id
game_id
season
position
I want to grab a player's id, name, games played, games won and winning percentage, which I know to be wins divided by total games played times 100. Total games played would be a count(*) and wins would be a count(*) where position is equal to 1. This will be done in a PHP function, so I also need the query to take into account season. There are other tables holding game and season information, but they are not relevent to this query.
So I've tried this query to grab season 1 winning percentages:
SELECT p.player_id,
CONCAT(p.firstname,' ',p.lastname) AS player_name,
COUNT(*) AS games_played,
(SELECT COUNT(*) FROM game_data WHERE player_id=p.player_id AND position=1 AND season=1) AS games_won,
(games_won/games_played)*100 AS winning_percentage
FROM game_data AS g
WHERE season=1
INNER JOIN players AS p
ON p.player_id=g.player_id
GROUP BY p.player_id
ORDER BY winning_percentage DESC
But it doesn't work. I get an error that games_won is an unknown field on the line that calculates the win percentage, so I am assuming I have to calculate this on the fly rather than post query. Any thoughts?