按州统计记录数
我们常常希望按另一列中某个特定取值来统计每条记录的数量。.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(____)