Aan de slagGa gratis aan de slag

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

Cursus bekijken

Oefeninstructies

  • Bouw een statement om te selecteren:
    • De kolom state uit de tabel census.
    • De som van de kolom pop2008 uit de tabel census.
    • De kolom census_division_name uit de tabel state_fact.
  • Voeg een .select_from() toe aan stmt om de tabellen census en state_fact te joinen op de kolommen state en name.
  • Groepeer de statement op de kolom name van de tabel state_fact.
  • Voer de statement stmt_grouped uit om alle records op te halen en sla die op als results.
  • 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)
Code bewerken en uitvoeren