开始使用免费开始使用

按州统计记录数

我们常常希望按另一列中某个特定取值来统计每条记录的数量。.group_by() 方法就可以回答这类查询。您可以将某一列传给 .group_by() 方法,并与 sum()count() 等聚合函数一起使用。与 .order_by() 方法类似,.group_by() 也可以接收多列作为参数。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • sqlalchemy 导入 func
  • 构建一个 select 语句,获取州字段的取值以及 age 字段取值的计数,并将其存为 stmt
  • 使用 .group_by() 方法按 state 列对语句进行分组。
  • 使用 connection 执行 stmt 获取计数,并将结果存为 results
  • 使用 results[0].keys() 打印返回结果的键/列名。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import func


# Build a query to select the state and count of ages by state: 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(____)
编辑并运行代码