计算各州在 2000 年与 2008 年普查中的人口差异
在最后这个练习中,您将编写查询,计算人口变化最大的州。查询仅显示前 10 个州。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 构建一个语句以:
- 选择
state。 - 计算 2008 年(
pop2008)与 2000 年(pop2000)的人口差值。
- 选择
- 使用在
stmt上的.group_by()方法,按census.columns.state对查询分组。 - 使用
.order_by()方法结合desc()函数,按'pop_change'降序排序。 - 使用
.limit()方法将查询限制为前10个州。 - 执行查询并将结果存为
results。 - 打印每条结果的州名和人口变化。此步骤已为您完成,直接提交答案即可查看结果!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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))