Aggregate Functions
Certain aggregate functions can also be used within SQLAlchemy by using the func module.
To import this module, execute:
from sqlalchemy.sql import func
Once func is imported, the following aggregate functions are available:
COUNT
The following example counts the number of records in a set of groups using the session object's query() method.rs = session.query(func.count(Contacts.Id).label("CustomCount"), Contacts.City).group_by(Contacts.City) for instance in rs: print("Count: ", instance.CustomCount) print("City: ", instance.City) print("---------")
You can also execute COUNT using the session object's execute() method:
rs = session.execute(Contacts_table.select().with_only_columns([func.count(Contacts_table.c.Id).label("CustomCount"), Contacts_table.c.City])group_by(Contacts_table.c.City)) for instance in rs:
SUM
This example calculates the cumulative amount of a numeric column in a set of groups.
rs = session.query(func.sum(Contacts.AnnualRevenue).label("CustomSum"), Contacts.City).group_by(Contacts.City) for instance in rs: print("Sum: ", instance.CustomSum) print("City: ", instance.City) print("---------")
You can also invoke SUM using the session object's execute() method.
rs = session.execute(Contacts_table.select().with_only_columns([func.sum(Contacts_table.c.AnnualRevenue).label("CustomSum"), Contacts_table.c.City]).group_by(Contacts_table.c.City)) for instance in rs:
AVG
This example uses the session object's query() method to calculate the average amount of a numeric column in a set of groups:rs = session.query(func.avg(Contacts.AnnualRevenue).label("CustomAvg"), Contacts.City).group_by(Contacts.City) for instance in rs: print("Avg: ", instance.CustomAvg) print("City: ", instance.City) print("---------")
You can also use the session object's execute() method to invoke AVG:
rs = session.execute(Contacts_table.select().with_only_columns([func.avg(Contacts_table.c.AnnualRevenue).label("CustomAvg"), Contacts_table.c.City]).group_by(Contacts_table.c.City)) for instance in rs:
MAX and MIN
This example finds the maximum value and minimum value of a numeric column in a set of groups.rs = session.query(func.max(Contacts.AnnualRevenue).label("CustomMax"), func.min(Contacts.AnnualRevenue).label("CustomMin"), Contacts.City).group_by(Contacts.City) for instance in rs: print("Max: ", instance.CustomMax) print("Min: ", instance.CustomMin) print("City: ", instance.City) print("---------")
You can also use the session object's execute() method to invoke MAX and MIN:
rs = session.execute(Contacts_table.select().with_only_columns([func.max(Contacts_table.c.AnnualRevenue).label("CustomMax"), func.min(Contacts_table.c.AnnualRevenue).label("CustomMin"), Contacts_table.c.City]).group_by(Contacts_table.c.City)) for instance in rs: