开始使用免费开始使用

按州统计人口总和

为避免出现像 count_1 这样的查询结果列名,您可以使用 .label() 方法为结果列命名。它附加在所用的函数方法后面,参数是您希望使用的列名。

我们可以将 func.sum().group_by() 搭配,按 State 计算人口总和,并用 label() 方法为输出命名。

我们也可以在 select 语句中使用之前先创建 func.sum() 表达式。写法与在 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(____)
编辑并运行代码