更多 join 練習
你可以沿用上一題建立的 select 敘述。不過,這次加點變化:只回傳部分欄位,並在 group_by() 子句中使用另一張資料表。
本練習屬於課程
Python 資料庫入門
練習說明
- 建立一個敘述以選取:
census資料表中的state欄位。census資料表中pop2008欄位的總和。state_fact資料表中的census_division_name欄位。
- 在
stmt後加入.select_from(),以state與name欄位將census與state_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)