Combining tables

Reporting in SQL

Tyler Pernes

Learning & Development Consultant

Goal report

Gold Medals by Demographic Group
(Western European Countries Only)
+----------+--------------------+-------+
| season   |  demographic_group | golds |
|----------+--------------------+-------|
| Winter   | Male Age 26+       | 13    |
| Winter   | Female Age 26+     | 8     |
| Summer   | Male Age 13-25     | 7     |
| Summer   | Female Age 13-25   | 6     |
| Winter   | Male Age 13-25     | 4     |
| Summer   | Male Age 26+       | 4     |
| Winter   | Female Age 13-25   | 4     |
| Summer   | Female Age 26+     | 2     |
+----------+--------------------+-------+
Reporting in SQL

Relevant tables

Reporting in SQL

Relevant tables

Reporting in SQL

Option A: JOIN first, UNION second

Reporting in SQL

Option A: JOIN first, UNION second

Step 1: Setup top query with JOIN

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM summer_games AS sg
JOIN athletes AS a 
ON sg.athlete_id = a.id;
Query ran successfully!
Reporting in SQL

Option A: JOIN first, UNION second

Step 2: Setup bottom query + UNION the two

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM summer_games AS sg
JOIN athletes AS a 
ON sg.athlete_id = a.id
UNION ALL
SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM winter_games AS wg
JOIN athletes AS a 
ON wg.athlete_id = a.id;
Reporting in SQL

Option B: UNION first, JOIN second

Reporting in SQL

Option B: UNION first, JOIN second

Step 1: Create initial UNION

SELECT 
    athlete_id, 
    gold  
FROM summer_games AS sg
UNION
SELECT 
    athlete_id, 
    gold  
FROM winter_games AS wg;
Reporting in SQL

Option B: UNION first, JOIN second

Step 2: Convert to subquery + JOIN

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM
    (SELECT 
         athlete_id, 
         gold  
    FROM summer_games AS sg
    UNION ALL
    SELECT athlete_id, gold  
    FROM winter_games AS wg) AS g
JOIN athletes AS a 
ON g.athlete_id = a.id;
Reporting in SQL

Comparison

Option A

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM summer_games AS sg
JOIN athletes AS a 
ON sg.athlete_id = a.id
UNION ALL
SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM winter_games AS wg
JOIN athletes AS a 
ON wg.athlete_id = a.id;

Option B

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM
    (SELECT 
         athlete_id, 
         gold  
    FROM summer_games AS sg
    UNION ALL
    SELECT athlete_id, gold  
    FROM winter_games AS wg) AS g
JOIN athletes AS a 
ON g.athlete_id = a.id;
Reporting in SQL

Key takeaways

  • Several ways to create the same report
  • Step-by-step = easier to troubleshoot
Reporting in SQL

Query time!

Reporting in SQL

Preparing Video For Download...