依州別計算人口總和
為了避免查詢結果出現像 count_1 這樣不清楚的欄位名稱,你可以使用 .label() 方法為計算出的欄位命名。這個方法會接在所使用的函式之後,參數就是你想要的欄位名稱。
我們可以把 func.sum() 和 .group_by() 搭配使用,取得依「State」分組的人口總和,並用 label() 方法為輸出欄位命名。
你也可以先建立 func.sum() 的運算式,再在 select 敘述中使用。做法與在 select 敘述裡相同,但先將它存進變數,接著在原本會放 func.sum() 的位置改用該變數。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
sqlalchemy匯入func。 - 建立一個運算式,計算
pop2008欄位的總和,並將其標記為'population'。 - 建立一個 select 敘述,取得
state欄位的值,以及pop2008的總和。 - 使用
.group_by()依state對敘述分組。 - 使用
connection執行stmt以取得計算結果,並將結果存為results。 - 使用
results[0].keys()列印回傳結果的鍵/欄位名稱。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import func
____
# Build an expression to calculate the sum of pop2008 labeled as population
pop2008_sum = func.sum(____).label(____)
# Build a query to select the state and sum of pop2008: 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(____)