Determine the percentage of population by gender and state
In this exercise, you will write a query to determine the percentage of the population in 2000 that comprised of women. You will group this query by state.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Import
case,castandFloatfromsqlalchemy. - Define a statement to select
stateand the percentage of women in 2000.- Inside
func.sum(), usecase()to select women (using thesexcolumn) frompop2000. Remember to specifyelse_=0if thesexis not'F'. - To get the percentage, divide the number of women in the year 2000 by the overall population in 2000. Cast the divisor -
census.columns.pop2000- toFloatbefore multiplying by 100.
- Inside
- Group the query by
state. - Execute the query and store it as
results. - Print
stateandpercent_femalefor each record. This has been done for you, so submit the answer to see the result.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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)