고유 데이터 개수 세기
영상에서 언급했듯이, SQLAlchemy의 func 모듈은 COUNT나 SUM 같은 내장 SQL 함수를 제공하여 집계 연산을 더 빠르고 효율적으로 수행할 수 있게 해요.
영상에서 Jason은 아래와 같이 census의 pop2008 열에 대해 합계를 구하기 위해 func.sum()을 사용했어요:
select([func.sum(census.columns.pop2008)])
반대로 pop2008의 값 개수를 세려면 func.count()를 다음과 같이 사용할 수 있어요:
select([func.count(census.columns.pop2008)])
더 나아가 pop2008의 고유한 값만 세고 싶다면 .distinct() 메서드를 함께 사용하면 됩니다:
select([func.count(census.columns.pop2008.distinct())])
이번 연습에서는 func.count()와 .distinct()를 사용하여 census에 있는 주(state)의 고유 개수를 구해 보겠습니다.
지금까지 ResultProxy에서 결과를 얻기 위해 .fetchall(), .fetchmany(), .first()를 사용했죠. ResultProxy에는 한 행과 한 열만 반환하는 쿼리에서 단일 값을 가져오는 .scalar() 메서드도 있어요.
단순히 count나 sum 값을 조회할 때 매우 유용합니다.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
census의state필드에서 고유한 값의 개수를 세는select문을 만드세요.stmt를 실행하여 개수를 가져오고 결과를distinct_state_count에 저장하세요.distinct_state_count값을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Build a query to count the distinct states values: stmt
stmt = select([____])
# Execute the query and store the scalar result: distinct_state_count
distinct_state_count = connection.execute(____).scalar()
# Print the distinct_state_count
print(____)