Combinare tabelle

Reportistica in SQL

Tyler Pernes

Learning & Development Consultant

Report obiettivo

Medaglie d'oro per gruppo demografico
(Solo paesi dell'Europa occidentale)
+----------+--------------------+-------+
| 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     |
+----------+--------------------+-------+
Reportistica in SQL

Tabelle rilevanti

Reportistica in SQL

Tabelle rilevanti

Reportistica in SQL

Opzione A: prima JOIN, poi UNION

Reportistica in SQL

Opzione A: prima JOIN, poi UNION

Passo 1: imposta la query in alto con JOIN

SELECT 
    athlete_id, 
    gender, 
    age, 
    gold  
FROM summer_games AS sg
JOIN athletes AS a 
ON sg.athlete_id = a.id;
Query eseguita correttamente!
Reportistica in SQL

Opzione A: prima JOIN, poi UNION

Passo 2: imposta la query in basso + UNION tra le due

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;
Reportistica in SQL

Opzione B: prima UNION, poi JOIN

Reportistica in SQL

Opzione B: prima UNION, poi JOIN

Passo 1: crea la UNION iniziale

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

Opzione B: prima UNION, poi JOIN

Passo 2: trasforma in sottoquery + 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;
Reportistica in SQL

Confronto

Opzione 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;

Opzione 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;
Reportistica in SQL

Punti chiave

  • Più modi per creare lo stesso report
  • Passo dopo passo = debug più semplice
Reportistica in SQL

Tempo di query!

Reportistica in SQL

Preparing Video For Download...