More practice with joins
You can use the same select statement you built in the last exercise, however,
let's add a twist and only return a few columns and use the other table in a
group_by() clause.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Build a statement to select:
- The
statecolumn from thecensustable. - The sum of the
pop2008column from thecensustable. - The
census_division_namecolumn from thestate_facttable.
- The
- Append a
.select_from()tostmtin order to join thecensusandstate_facttables by thestateandnamecolumns. - Group the statement by the
namecolumn of thestate_facttable. - Execute the statement
stmt_groupedto get all the records and save it asresults. - Submit the answer to loop over the
resultsobject and print each record.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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)