Kombinování tabulek

Reporting in SQL

Tyler Pernes

Learning & Development Consultant

Cílový 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

Relevantní tabulky

Reporting in SQL

Relevantní tabulky

Reporting in SQL

Možnost A: nejprve JOIN, potom UNION

Reporting in SQL

Možnost A: nejprve JOIN, potom UNION

Krok 1: Nastavení horního dotazu pomocí 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

Možnost A: nejprve JOIN, potom UNION

Krok 2: Nastavení spodního dotazu + UNION dvou

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

Možnost B: nejprve UNION, potom JOIN

Reporting in SQL

Možnost B: nejprve UNION, potom JOIN

Krok 1: Vytvoření počátečního UNION

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

Možnost B: nejprve UNION, potom JOIN

Krok 2: Převod na poddotaz + 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

Porovnání

Možnost 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;

Možnost 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

Klíčové poznatky

  • Existuje více způsobů, jak sestavit stejný report
  • Postupný přístup = snazší ladění
Reporting in SQL

Čas na dotazy!

Reporting in SQL

Preparing Video For Download...