Count of records by state
Often, we want to get a count for each record with a particular value in another
column. The .group_by() method helps answer this type of query. You can pass a column
to the .group_by() method and use in an aggregate function like sum() or count().
Much like the .order_by() method, .group_by() can take multiple columns as
arguments.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Import
funcfromsqlalchemy. - Build a
selectstatement to get the value of the state field and a count of the values in theagefield, and store it asstmt. - Use the
.group_by()method to group the statement by thestatecolumn. - Execute
stmtusing theconnectionto get the count and store the results asresults. - Print the keys/column names of the results returned using
results[0].keys().
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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(____)