I have a series of button tag.
SELECT team, COUNT( team ) AS pld,
SUM( IF( Pts = 3, 1, 0 ) ) AS W,
SUM( IF( Pts = 1, 1, 0 ) ) AS D,
SUM( IF( Pts = 0, 1, 0 ) ) AS L,
SUM( Pts ) AS Pts,
SUM( GF ) AS GF,
SUM( GA ) AS GA,
SUM( GF ) - SUM( GA ) AS GD
FROM (
SELECT home_team_id AS team,
home_goal_number AS GF,
away_goal_number AS GA,
CASE
WHEN home_goal_number > away_goal_number
THEN 3
WHEN home_goal_number = away_goal_number
THEN 1
ELSE 0
END AS Pts
FROM matches
UNION ALL
SELECT away_team_id AS team,
away_goal_number AS GF,
home_goal_number AS GA,
CASE
WHEN away_goal_number > home_goal_number
THEN 3
WHEN away_goal_number = home_goal_number
THEN 1
ELSE 0
END AS Pts
FROM matches
) AS tab
GROUP BY team
ORDER BY Pts DESC
This work perfectly. There’s only one problem. If two teams end the league with the same points, the first way to remove the ambiguity is understand who win the direct match.
How can I modify this query to do that?
If you consider the only way to know there is a draw is to calculate the points using the query you have shown, you can see it is not an easy task to add the direct match winner information to the current query.
I would consider putting the query you have in a VIEW and then creating a new query to use the view and calculate the overall winner where the number of points for two teams are equal.
As I said in my comment, what do you do when the direct match is a draw or when more than two teams have the same number of points at the end of the competition? These cases are possible but difficult to code a solution for.
An alternative is to use goal difference but that may require your league to change their rules 🙂