各州紀錄數量
我們常常想要針對某欄位中具有特定值的每筆紀錄進行計數。.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(____)