Zacznij terazZacznij za darmo

Więcej ćwiczeń z łączeniem tabel

Możesz wykorzystać tę samą instrukcję SELECT, którą zbudowano w poprzednim ćwiczeniu – tym razem jednak zwrócimy tylko kilka kolumn i użyjemy drugiej tabeli w klauzuli group_by().

To ćwiczenie jest częścią kursu

Wprowadzenie do baz danych w Pythonie

Zobacz kurs

Instrukcje do ćwiczenia

  • Zbuduj instrukcję, która wybiera:
    • Kolumnę state z tabeli census.
    • Sumę wartości kolumny pop2008 z tabeli census.
    • Kolumnę census_division_name z tabeli state_fact.
  • Dołącz .select_from() do stmt, aby połączyć tabele census i state_fact po kolumnach state i name.
  • Pogrupuj instrukcję według kolumny name z tabeli state_fact.
  • Wykonaj instrukcję stmt_grouped, aby pobrać wszystkie rekordy, i zapisz wynik jako results.
  • Prześlij odpowiedź, aby przeiterować po obiekcie results i wyświetlić każdy rekord.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

# 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)
Edytuj i uruchom kod