開始使用免費開始

各州紀錄數量

我們常常想要針對某欄位中具有特定值的每筆紀錄進行計數。.group_by() 方法能幫你回答這類查詢。你可以把某個欄位傳入 .group_by() 方法,並搭配彙總函式(例如 sum()count())使用。和 .order_by() 類似,.group_by() 也可以接受多個欄位作為引數。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • sqlalchemy 匯入 func
  • 建立一個 select 陳述式,取得州別欄位的值以及 age 欄位的計數,並將其存為 stmt
  • 使用 .group_by() 方法,依 state 欄位對陳述式分組。
  • 使用 connection 執行 stmt 以取得計數,並將結果存為 results
  • 使用 results[0].keys() 列印回傳結果的鍵/欄名。

動手互動練習

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

# Import func


# Build a query to select the state and count of ages by state: stmt
stmt = select([____, ____])

# Group stmt by state
stmt = stmt.group_by(____)

# Execute the statement and store all the records: results
results = connection.execute(____).fetchall()

# Print results
print(results)

# Print the keys/column names of the results returned
print(____)
編輯並執行程式碼