開始使用免費開始

使用 ORDER BY 排序你的 SQL 紀錄

你也可以對 SQL 查詢結果進行排序。例如,如果你想從 Chinook 資料庫的 Customer 資料表取得所有紀錄,並依 SupportRepId 欄位遞增排序,可以用以下查詢:

"SELECT * FROM Customer ORDER BY SupportRepId"

其實,任何 SELECT 敘述都可以依任一欄位排序。

在這個互動練習中,你會選取 Employee 資料表的所有紀錄,並依 BirthDate 欄位遞增排序。

所需的套件已經匯入如下:

import pandas as pd
from sqlalchemy import create_engine

開始查詢吧!

本練習屬於課程

Python 資料匯入入門

檢視課程

練習說明

  • 使用 create_engine() 函式為 SQLite 資料庫 Chinook.sqlite 建立引擎,並指定給變數 engine
  • 在情境管理器(context manager)中,執行查詢:從 Employee 資料表選取全部紀錄,並依 BirthDate 欄位遞增排序。將結果指定給 rs
  • 呼叫 pd.DataFrame() 時,對 rs 套用 fetchall() 方法以擷取所有紀錄。將它們存入 DataFrame df
  • 將 DataFrame 的欄名設定為對應到資料表欄位的名稱。

動手互動練習

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

# Create engine: engine


# Open engine in context manager
with engine.connect() as con:
    rs = ____
    df = ____

    # Set the DataFrame's column names


# Print head of DataFrame
print(df.head())
編輯並執行程式碼