始める無料で始める

階層データでの関数と 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)

コードを編集して実行