比較各州在 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))