始める無料で始める

JOINの練習をさらに進めましょう

前の演習で作成したのと同じ select 文を使えますが、ここでは少し工夫して、返す列を一部に絞り、もう一方のテーブルを group_by() で活用してみます。

この演習はコースの一部です

Pythonで学ぶデータベース入門

コースを見る

演習の手順

  • 次を選択するステートメントを作成します:
    • census テーブルの state
    • census テーブルの pop2008 列の合計
    • state_fact テーブルの census_division_name
  • stmt.select_from() を追加し、state 列と name 列で censusstate_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)
コードを編集して実行