단일 컬럼으로 정렬하기
결과를 특정 필드로 정렬하려면 .order_by() 메서드를 사용해요. 기본적으로 .order_by()는 지정한 컬럼을 기준으로 오름차순(낮은 값에서 높은 값) 정렬을 수행합니다. 정렬하고 싶은 컬럼 이름을 .order_by()에 전달하기만 하면 됩니다.
예를 들어, 영상에서 Jason은 결과를 state 컬럼 기준으로 정렬하기 위해 stmt.order_by(census.columns.state)를 사용했어요.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
census테이블에서state컬럼의 모든 레코드를 선택하세요. 이를 위해census.columns.state를 리스트로 감싸select()에 전달하세요.- 결과를
state컬럼 기준으로 정렬하도록.order_by()를 이어 붙이세요. connection의.execute()메서드를 사용해stmt를 실행하고,.fetchall()로 모든 결과를 가져오세요.results의 처음 10개 행을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Build a query to select the state column: stmt
stmt = ____
# Order stmt by the state column
stmt = ____
# Execute the query and store the results: results
results = ____
# Print the first 10 results
print(____[:10])