Ancora pratica con le join
Puoi riutilizzare la stessa select che hai costruito nell'esercizio precedente; aggiungiamo però una variante: restituisci solo alcune colonne e usa l'altra tabella in una clausola group_by().
Questo esercizio fa parte del corso
Introduzione ai database in Python
Istruzioni dell'esercizio
- Costruisci un'istruzione per selezionare:
- La colonna
statedalla tabellacensus. - La somma della colonna
pop2008dalla tabellacensus. - La colonna
census_division_namedalla tabellastate_fact.
- La colonna
- Aggiungi un
.select_from()astmtper fare la join tra le tabellecensusestate_facttramite le colonnestateename. - Raggruppa l'istruzione per la colonna
namedella tabellastate_fact. - Esegui l'istruzione
stmt_groupedper ottenere tutti i record e salvala comeresults. - Invia la risposta per iterare sull'oggetto
resultse stampare ogni record.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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)