统计不同的数据
正如视频中提到的,SQLAlchemy 的 func 模块提供了对内置 SQL 函数的访问,可以让计数、求和等操作更快、更高效。
在视频中,Jason 使用 func.sum() 来获取 census 表中 pop2008 列的总和,如下所示:
select([func.sum(census.columns.pop2008)])
如果您想计数 pop2008 中的值数量,可以像这样使用 func.count():
select([func.count(census.columns.pop2008)])
此外,如果您只想统计 pop2008 的不同取值数量,可以使用 .distinct() 方法:
select([func.count(census.columns.pop2008.distinct())])
在本练习中,您将练习使用 func.count() 和 .distinct() 来统计 census 中不同州名的数量。
到目前为止,您已经见过在 ResultProxy 上使用 .fetchall()、.fetchmany() 和 .first() 来获取结果。ResultProxy 还有一个名为 .scalar() 的方法,用于获取只返回单行单列的查询值。
当您只查询计数或总和时,这会非常有用。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 构建一个
select语句,用于统计census表中state字段的不同取值数量。 - 执行
stmt获取计数,并将结果保存为distinct_state_count。 - 打印
distinct_state_count的值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Build a query to count the distinct states values: stmt
stmt = select([____])
# Execute the query and store the scalar result: distinct_state_count
distinct_state_count = connection.execute(____).scalar()
# Print the distinct_state_count
print(____)