開始使用免費開始

計算兩個欄位之間的差異

在查詢中,你常常需要進行數學運算,例如想計算 2000 年到 2008 年的人口變化。對於數值的運算,SQLAlchemy 的運算子用法和 Python 相同。

你可以使用這些運算子進行加法(+)、減法(-)、乘法(*)、除法(/)和取餘數(%)。注意:在非數值的欄位型別上,行為會有所不同。

現在就找出 2000 到 2008 年人口成長最多的前 5 個州。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 定義名為 stmt 的 select 陳述式,回傳:
    • i)census 資料表的州別欄(census.columns.state)。
    • ii)2008 年(census.columns.pop2008)減去 2000 年(census.columns.pop2000)的人口數差,並標記為 'pop_change'
  • census.columns.state 對陳述式進行分組。
  • 依人口變化量('pop_change')進行遞減排序;做法是傳入 desc('pop_change')
  • 在前一個陳述式上使用 .limit(),只回傳 5 筆紀錄。
  • 執行該陳述式並使用 fetchall() 取回所有紀錄。
  • 列印語句已為你寫好。送出答案即可查看結果!

動手互動練習

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

# Build query to return state names by population difference from 2008 to 2000: stmt
stmt = select([____, (____-____).label(____)])

# Append group by for the state: stmt_grouped
stmt_grouped = stmt.group_by(____)

# Append order by for pop_change descendingly: stmt_ordered
stmt_ordered = stmt_grouped.order_by(____)

# Return only 5 results: stmt_top5
stmt_top5 = ____

# Use connection to execute stmt_top5 and fetch all results
results = connection.execute(____).fetchall()

# Print the state and population change for each record
for result in results:
    print('{}:{}'.format(result.state, result.pop_change))
編輯並執行程式碼