开始使用免费开始使用

继续练习连接查询

您可以复用上一个练习中构建的 select 语句。不过这次加一点变化:只返回少量列,并在 group_by() 子句中使用另一张表。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • 构建一个语句以选择:
    • 来自 census 表的 state 列。
    • 来自 census 表的 pop2008 列的总和。
    • 来自 state_fact 表的 census_division_name 列。
  • stmt 追加 .select_from(),按 statename 两列将 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)
编辑并运行代码