開始使用免費開始

以單一欄位排序

若要依某個欄位排序查詢結果,使用 .order_by() 方法。預設情況下,.order_by() 會依提供的欄位由小到大排序。你只需要把想排序的欄位名稱傳給 .order_by() 即可。

例如在影片中,Jason 使用 stmt.order_by(census.columns.state),讓結果依 state 欄位排序。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • census 資料表選取 state 欄位的所有紀錄。為此,將 census.columns.state 以清單形式傳給 select()
  • 串接 .order_by(),讓結果依 state 欄位排序。
  • 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])
編輯並執行程式碼