주(state)별 레코드 개수 세기
특정 열의 값별로 레코드 개수를 집계하고 싶을 때가 많습니다.
이럴 때 .group_by() 메서드가 유용합니다. .group_by()에 열을 전달하고 sum() 또는 count() 같은 집계 함수를 함께 사용할 수 있어요.
.order_by() 메서드와 마찬가지로 .group_by()도 여러 열을 인자로 받을 수 있습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
sqlalchemy에서func를 가져오세요.state필드 값과age필드 값의 개수를 가져오는select문을 만들고, 이를stmt에 저장하세요..group_by()메서드를 사용해state열로 그룹화하세요.connection을 사용해stmt를 실행하여 개수를 구하고, 결과를results에 저장하세요.results[0].keys()를 사용해 반환된 결과의 키/열 이름을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import func
# Build a query to select the state and count of ages by state: stmt
stmt = select([____, ____])
# Group stmt by state
stmt = stmt.group_by(____)
# Execute the statement and store all the records: results
results = connection.execute(____).fetchall()
# Print results
print(results)
# Print the keys/column names of the results returned
print(____)