Here is the problem as follows:
team | season | games_won |
---|---|---|
San Francisco Giants | 2010 | 92 |
San Francisco Giants | 2011 | 86 |
San Francisco Giants | 2012 | 94 |
San Francisco Giants | 2013 | 76 |
San Francisco Giants | 2014 | 88 |
Los Angeles Dodgers | 2010 | 80 |
Los Angeles Dodgers | 2011 | 82 |
Los Angeles Dodgers | 2012 | 86 |
Los Angeles Dodgers | 2013 | 92 |
Los Angeles Dodgers | 2014 | 94 |
Write the SQL to generate the following output, where the second column is the season in which each team had the most wins. The Giants & Dodgers are shown for illustrative purposes below, but the SQL should pull all teams at once:
I have two methods to solve this:
Method 1
WITH cte_wins
AS (SELECT team,
Max(games_won) AS most_wins
FROM table_wins
GROUP BY team)
SELECT table_wins.team,
table_wins.season AS season_with_most_wins
FROM table_wins
JOIN cte_wins
ON cte_wins.team = table_wins.team
AND cte_wins.most_wins = table_wins.games_won
Method 2
SELECT table_wins.team,
table_wins.season AS season_with_most_wins
FROM table_wins
JOIN (SELECT team,
Max(games_won) AS most_wins
FROM table_wins
GROUP BY team) AS sub
ON sub.team = table_wins.team
AND sub.most_wins = table_wins.games_won
Method 3
Is there a better method to solve this question? I am wondering if my approach is just bad and maybe I should try something else. Any and all feedback would be welcomed.