SQL Lab 3: Answers
Lab 3-1: How many teams played in the league in each year?
SELECT year, COUNT(*) FROM teams GROUP BY year;
Lab 3-2: For each team, what is the average number of wins per season, in the 21st century?
SELECT name, AVG(wins) FROM teams WHERE year > 2000 GROUP BY name;
Lab 3-3: In the modern era (1960-present), how many regular season games did the best team win each season?
Challenge: Try to include the team's name in the results. Is it accurate?
SELECT year, MAX(wins)
FROM teams
WHERE year >= 1960
GROUP BY year
ORDER BY MAX(wins) DESC;
Adding name
is not reliable because it is not part of the GROUP BY
clause. The only columns that can be in the SELECT
are either also in the GROUP BY
or are aggregate functions.