Reporting in SQL
Tyler Pernes
Learning & Development Consultant
PARTITION BY
= range of calculationORDER BY
= order of rows when running calculationTotal bronze medals
SELECT
country_id,
athlete_id,
SUM(bronze) OVER () AS total_bronze
FROM summer_games;
+-------------+-------------+---------------+
| country_id | athlete_id | total_bronze |
|-------------|-------------|---------------|
| 11 | 77505 | 141 |
| 11 | 11673 | 141 |
| 14 | 85554 | 141 |
| 14 | 76433 | 141 |
+-------------+-------------+---------------+
Country bronze medals
SELECT
country_id,
athlete_id,
SUM(bronze) OVER (PARTITION BY country_id) AS total_bronze
FROM summer_games
+-------------+-------------+---------------+
| country_id | athlete_id | total_bronze |
|-------------|-------------|---------------|
| 11 | 77505 | 12 |
| 11 | 11673 | 12 |
| 14 | 85554 | 5 |
| 14 | 76433 | 5 |
+-------------+-------------+---------------+
SUM()
AVG()
MIN()
MAX()
LAG()
and LEAD()
LAG()
and LEAD()
ROW_NUMBER()
and RANK()
original_table
+----------+-----------+---------+
| team_id | player_id | points |
|----------|-----------|---------|
| 1 | 4123 | 3 |
| 1 | 5231 | 6 |
| 2 | 8271 | 5 |
+----------+-----------+---------+
desired_report
+----------+-------------+---------------+
| team_id | team_points | league_points |
|----------|-------------|---------------|
| 1 | 9 | 43 |
| 2 | 12 | 43 |
| 3 | 22 | 43 |
+----------+-------------+---------------+
Final query
SELECT
team_id,
SUM(points) AS team_points,
SUM(SUM(points)) OVER () AS league_points
FROM original_table
GROUP BY team_id;
SELECT
team_id,
SUM(points) AS team_points,
SUM(points) OVER () AS league_points
FROM original_table
GROUP BY team_id;
ERROR: points must be an aggregation or appear in a GROUP BY statement.
Step 1: Total bronze medals per country
SELECT country_id, SUM(bronze) as bronze_medals
FROM summer_games
GROUP BY country_id;
Step 2: Convert to subquery and take the max
SELECT MAX(bronze_medals)
FROM
(SELECT country_id, SUM(bronze) as bronze_medals
FROM summer_games
GROUP BY country_id) AS subquery;
Reporting in SQL