Meer oefenen met joins
Je kunt dezelfde select-statement gebruiken die je in de vorige oefening hebt gemaakt, maar
laten we er een draai aan geven: retourneer slechts een paar kolommen en gebruik de andere tabel in een
group_by()-clausule.
Deze oefening maakt deel uit van de cursus
Introductie tot databases in Python
Oefeninstructies
- Bouw een statement om te selecteren:
- De kolom
stateuit de tabelcensus. - De som van de kolom
pop2008uit de tabelcensus. - De kolom
census_division_nameuit de tabelstate_fact.
- De kolom
- Voeg een
.select_from()toe aanstmtom de tabellencensusenstate_factte joinen op de kolommenstateenname. - Groepeer de statement op de kolom
namevan de tabelstate_fact. - Voer de statement
stmt_groupeduit om alle records op te halen en sla die op alsresults. - Verzend het antwoord om over het
results-object te loopen en elk record te printen.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# Build a statement to select the state, sum of 2008 population and census
# division name: stmt
stmt = select([
____,
func.sum(____),
____
])
# Append select_from to join the census and state_fact tables by the census state and state_fact name columns
stmt_joined = stmt.select_from(
census.join(____, census.columns.____ == state_fact.columns.____)
)
# Append a group by for the state_fact name column
stmt_grouped = stmt_joined.group_by(____)
# Execute the statement and get the results: results
results = connection.execute(____).fetchall()
# Loop over the results object and print each record.
for record in results:
print(record)