2000年と2008年の国勢調査から州ごとの差分を求める
この最後の演習では、人口が最も変化した州を計算するクエリを書きます。表示は上位10州のみに絞り込みます。
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
- 次の内容のステートメントを作成します:
stateを選択します。- 2008年(
pop2008)と2000年(pop2000)の人口差を計算します。
.group_by()メソッドをstmtに対して使い、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))