Pojďme na to krok za krokem:
Vyberte vyhrané zápasy doma a skóre doma:
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
Nazvěme tento výsledek HOME_GAMES.
Vyberte vyhrané zápasy a skóre venkovních zápasů:
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
Nazvěme tento výsledek AWAY_GAMES.
Vyberte celkový počet vyhraných her a celkové skóre:
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
==> Dejte vše dohromady nahrazením AWAY_GAMES a 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