두 열 간의 차이 계산하기
쿼리에서 수학 연산이 필요한 경우가 자주 있습니다. 예를 들어 2000년부터 2008년까지 인구 변화를 계산하고 싶을 수 있죠. 숫자에 대한 수학 연산은 SQLAlchemy에서도 Python과 동일한 방식으로 동작합니다.
이 연산자들을 사용해 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/), 나머지(%) 연산을 수행할 수 있습니다. 참고: 숫자가 아닌 열 타입에서는 동작이 다를 수 있습니다.
이제 2000년부터 2008년까지 인구가 가장 많이 증가한 상위 5개 주를 찾아보겠습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
stmt라는 이름의 select 문을 정의해 다음을 반환하세요:- i)
census테이블의 state 열(census.columns.state). - ii) 2008년(
census.columns.pop2008)과 2000년(census.columns.pop2000)의 인구 수 차이를'pop_change'라는 라벨로 표시한 값.
- i)
- 문을
census.columns.state로 그룹화하세요. - 인구 변화량(
'pop_change')을 기준으로 내림차순 정렬하세요. 이를 위해desc('pop_change')를 전달하세요. - 이전 문에
.limit()메서드를 사용해 레코드를 5개만 반환하세요. - 문을 실행하고
fetchall()로 레코드를 가져오세요. - print 구문은 이미 작성되어 있습니다. 결과를 보려면 답변을 제출하세요!
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Build query to return state names by population difference from 2008 to 2000: stmt
stmt = select([____, (____-____).label(____)])
# Append group by for the state: stmt_grouped
stmt_grouped = stmt.group_by(____)
# Append order by for pop_change descendingly: stmt_ordered
stmt_ordered = stmt_grouped.order_by(____)
# Return only 5 results: stmt_top5
stmt_top5 = ____
# Use connection to execute stmt_top5 and fetch all results
results = connection.execute(____).fetchall()
# Print the state and population change for each record
for result in results:
print('{}:{}'.format(result.state, result.pop_change))