Нека го направим стъпка по стъпка:
Изберете спечелените игри у дома и резултата у дома:
SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G WHERE
G.team_id = T.team_id #See 3. query and you'll understand
G.home_score > away_score
Нека наречем този резултат HOME_GAMES.
Изберете спечелените игри и резултата от гостуванията:
SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
WHERE
G.team_id = T.team_id #See 3. query and you'll understand
G.away_score > G.home_score
Нека наречем този резултат AWAY_GAMES.
Изберете общия брой спечелени игри и общия резултат:
SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM
(AWAY_GAMES) AS A, (HOME_GAMES) AS H, teams T
ORDER BY total_wins, total_score
==> Съберете всичко, като замените AWAY_GAMES и HOME_GAMES:
SELECT (A.wins + H.wins) AS total_wins, (A.score + H.score) AS total_score FROM
(SELECT COUNT(*) as wins, SUM(G.away_score) as score FROM games G
WHERE
G.team_id = T.team_id #See 3. and you'll understand
G.away_score > G.home_score) AS A,
(SELECT COUNT(*) as wins, SUM(G.home_score) as score FROM games G
WHERE
G.team_id = T.team_id #See 3. and you'll understand
G.home_score > away_score) AS H,
teams T
ORDER BY total_wins, total_score