开始使用免费开始使用

按性别与州计算人口百分比

在本练习中,您将编写查询来计算 2000 年女性占总人口的百分比。您将按州对结果进行分组。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • sqlalchemy 导入 casecastFloat
  • 定义一条语句,选择 state 和 2000 年的女性占比。
    • func.sum() 中,使用 case()pop2000 中选择女性(使用 sex 列)。如果 sex 不是 'F',请记得指定 else_=0
    • 若要得到百分比,将 2000 年女性人数除以 2000 年总人口。将被除数 census.columns.pop2000 转换为 Float,然后再乘以 100。
  • state 对查询分组。
  • 执行查询,并将其保存为 results
  • 为每条记录打印 statepercent_female。这部分已为您完成,请直接提交答案查看结果。

交互式实操练习

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

# import case, cast and Float from sqlalchemy
from sqlalchemy import ____, ____, ____

# Build a query to calculate the percentage of women in 2000: stmt
stmt = select([____,
    (func.sum(
        ____([
            (____ == 'F', ____)
        ], else_=0)) /
     cast(func.sum(____), ____) * 100).label('percent_female')
])

# Group By state
stmt = stmt.group_by(____)

# Execute the query and store the results: results
results = connection.execute(____).fetchall()

# Print the percentage
for result in results:
    print(result.state, result.percent_female)
编辑并运行代码