在階層式資料中運用函式與 group_by
在階層式資料表中,常見的需求是彙總資料。要彙總資料,必須留意你用來執行 group_by 的別名,以及用於聚合函式的資料表。
在這裡,你的任務是取得每位經理所管理的員工人數。
本練習屬於課程
Python 資料庫入門
練習說明
- 將
employees資料表建立別名並命名為managers。 - 建立查詢,選取
managers資料表的name欄位,以及其員工人數的計數。func.count()已經匯入,會很實用!請用它來計算employees資料表的id欄位。 - 使用
.where()子句,篩選出managers資料表的id欄位與employees資料表的mgr欄位相等的紀錄。 - 依據
managers資料表的name欄位進行群組。 - 執行該查詢並儲存所有結果。列印經理名稱與其員工數。這段程式碼已替你寫好,直接送出答案看看結果吧!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Make an alias of the employees table: managers
managers = ____
# Build a query to select names of managers and counts of their employees: stmt
stmt = select([____, func.count(____)])
# Append a where clause that ensures the manager id and employee mgr are equal
stmt_matched = stmt.____
# Group by Managers Name
stmt_grouped = stmt_matched.group_by(____)
# Execute statement: results
results = connection.execute(stmt_grouped).fetchall()
# print manager
for record in results:
print(record)