JOINの練習をさらに進めましょう
前の演習で作成したのと同じ select 文を使えますが、ここでは少し工夫して、返す列を一部に絞り、もう一方のテーブルを group_by() で活用してみます。
この演習はコースの一部です
Pythonで学ぶデータベース入門
演習の手順
- 次を選択するステートメントを作成します:
censusテーブルのstate列censusテーブルのpop2008列の合計state_factテーブルのcensus_division_name列
stmtに.select_from()を追加し、state列とname列でcensusとstate_factテーブルを結合します。- ステートメントを
state_factテーブルのname列でグループ化します。 - ステートメント
stmt_groupedを実行してすべてのレコードを取得し、resultsに保存します。 resultsオブジェクトをループして各レコードを出力し、回答を送信してください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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)