Determine the difference by state from the 2000 and 2008 censuses
In this final exercise, you will write a query to calculate the states that changed the most in population. You will limit your query to display only the top 10 states.
本练习是课程的一部分
Introduction to Databases in Python
练习说明
- Build a statement to:
- Select
state. - Calculate the difference in population between 2008 (
pop2008) and 2000 (pop2000).
- Select
- Group the query by
census.columns.stateusing the.group_by()method onstmt. - Order by
'pop_change'in descending order using the.order_by()method with thedesc()function on'pop_change'. - Limit the query to the top
10states using the.limit()method. - Execute the query and store it as
results. - Print the state and the population change for each result. This has been done for you, so submit the answer to see the result!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Build query to return state name and population difference from 2008 to 2000
stmt = select([____,
(____-____).label('pop_change')
])
# Group by State
stmt = stmt.____(____)
# Order by Population Change
stmt = stmt.____(____)
# Limit to top 10
stmt = stmt.____(____)
# Use connection to execute the statement and fetch all results
results = connection.execute(____).fetchall()
# Print the state and population change for each record
for result in results:
print('{}:{}'.format(result.state, result.pop_change))