继续练习连接查询
您可以复用上一个练习中构建的 select 语句。不过这次加一点变化:只返回少量列,并在 group_by() 子句中使用另一张表。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 构建一个语句以选择:
- 来自
census表的state列。 - 来自
census表的pop2008列的总和。 - 来自
state_fact表的census_division_name列。
- 来自
- 给
stmt追加.select_from(),按state与name两列将census表与state_fact表连接。 - 按
state_fact表的name列对语句分组。 - 执行语句
stmt_grouped,获取所有记录并保存为results。 - 提交答案以遍历
results对象并打印每条记录。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Build a statement to select the state, sum of 2008 population and census
# division name: stmt
stmt = select([
____,
func.sum(____),
____
])
# Append select_from to join the census and state_fact tables by the census state and state_fact name columns
stmt_joined = stmt.select_from(
census.join(____, census.columns.____ == state_fact.columns.____)
)
# Append a group by for the state_fact name column
stmt_grouped = stmt_joined.group_by(____)
# Execute the statement and get the results: results
results = connection.execute(____).fetchall()
# Loop over the results object and print each record.
for record in results:
print(record)