開始使用免費開始

更多 join 練習

你可以沿用上一題建立的 select 敘述。不過,這次加點變化:只回傳部分欄位,並在 group_by() 子句中使用另一張資料表。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 建立一個敘述以選取:
    • census 資料表中的 state 欄位。
    • census 資料表中 pop2008 欄位的總和。
    • state_fact 資料表中的 census_division_name 欄位。
  • stmt 後加入 .select_from(),以 statename 欄位將 censusstate_fact 兩張資料表做 join。
  • state_fact 資料表的 name 欄位為基準進行分組(group by)。
  • 執行敘述 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)
編輯並執行程式碼