開始使用免費開始

以多欄位排序

你可以在 .order_by() 方法中傳入多個引數,依多個欄位排序。事實上,也能對每個欄位分別指定遞增或遞減的排序方式。.order_by() 中的欄位會依從左到右的順序完整排序。也就是說,會先把第一個欄位完全排好序,接著在第一個欄位每個相同值的群組內,再依 .order_by() 中的下一個欄位排序。這個流程會重複,直到 .order_by() 中的所有欄位都完成排序為止。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • census 資料表選取 stateage 兩個欄位的所有紀錄。
  • 使用 .order_by(),將輸出依 state 遞增排序,並依 age 遞減排序。(注意:desc 已經匯入)
  • connection 上以 .execute() 執行 stmt,並以 .fetchall() 取回所有結果。
  • 列印前 20 筆結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Build a query to select state and age: stmt
stmt = select([____, ____])

# Append order by to ascend by state and descend by age
stmt = stmt.order_by(____, ____)

# Execute the statement and store all the records: results
results = ____

# Print the first 20 results
print(____)
編輯並執行程式碼