계층형 데이터에서 함수와 group_by 활용하기
계층형 테이블의 데이터를 집계(roll up)해야 하는 경우가 자주 있습니다. 집계를 할 때는 어떤 별칭으로 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)