CData Python Connector for FreshBooks

Build 20.0.7587

Aggregate Functions

Certain aggregate functions can also be used within SQLAlchemy by using the func module. First, you will need to import it:

from sqlalchemy.sql import func

Once imported, the following aggregate functions are available:

COUNT

This example counts the number of records in a set of groups using the session object's query() method.

for instance in session.query(func.count(Clients.Id).label("CustomCount"), Clients.Email).group_by(Clients.Email):
	print("Count: ", instance.CustomCount)
	print("Email: ", instance.Email)
	print("---------")

Alternatively, you can execute COUNT using the session object's execute() method.

for instance in session.execute(Clients_table.select().with_only_columns([func.count(Clients_table.c.Id).label("CustomCount"), Clients_table.c.Email])group_by(Clients_table.c.Email)):

SUM

This example calculates the cumulative amount of a numeric column in a set of groups.

for instance in session.query(func.sum(Clients.AnnualRevenue).label("CustomSum"), Clients.Email).group_by(Clients.Email):
	print("Sum: ", instance.CustomSum)
	print("Email: ", instance.Email)
	print("---------")

Alternatively, you can invoke SUM using the session object's execute() method.

for instance in session.execute(Clients_table.select().with_only_columns([func.sum(Clients_table.c.AnnualRevenue).label("CustomSum"), Clients_table.c.Email])group_by(Clients_table.c.Email)):

AVG

This example calculates the average amount of a numeric column in a set of groups using the session object's query() method.

for instance in session.query(func.avg(Clients.AnnualRevenue).label("CustomAvg"), Clients.Email).group_by(Clients.Email):
	print("Avg: ", instance.CustomAvg)
	print("Email: ", instance.Email)
	print("---------")

Alternatively, you can invoke AVG using the session object's execute() method.

for instance in session.execute(Clients_table.select().with_only_columns([func.avg(Clients_table.c.AnnualRevenue).label("CustomAvg"), Clients_table.c.Email])group_by(Clients_table.c.Email)):

MAX and MIN

This example finds the maximum value and minimum value of a numeric column in a set of groups.

for instance in session.query(func.max(Clients.AnnualRevenue).label("CustomMax"), func.min(Clients.AnnualRevenue).label("CustomMin"), Clients.Email).group_by(Clients.Email):
	print("Max: ", instance.CustomMax)
	print("Min: ", instance.CustomMin)
	print("Email: ", instance.Email)
	print("---------")

Alternatively, you can invoke MAX and MIN using the session object's execute() method.

for instance in session.execute(Clients_table.select().with_only_columns([func.max(Clients_table.c.AnnualRevenue).label("CustomMax"), func.min(Clients_table.c.AnnualRevenue).label("CustomMin"), Clients_table.c.Email])group_by(Clients_table.c.Email)):

Copyright (c) 2020 CData Software, Inc. - All rights reserved.
Build 20.0.7587