開始使用免費開始

在階層式資料中運用函式與 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)

編輯並執行程式碼