Reference > Functions > Aggregate
Avg
- 2005
- 2008
- 2012
- 2014
- 2016
- 2017
- 2019
- 2022
- 2005, 2008, 2012, 2014, 2016, 2017, 2019, 2022
Avg (Average) Aggregate Function
Use the Avg
function to return the average of a set of values, ignoring null values.
Syntax
db.fx.Avg({expression})[.Distinct()]
Arguments
- expression
- Distinct()
Returns
expression type | return type |
---|---|
AnyElement<byte> | int |
AnyElement<byte?> | int? |
AnyElement<short> | int |
AnyElement<short?> | int? |
AnyElement<int> | int |
AnyElement<int?> | int? |
AnyElement<long> | long |
AnyElement<long?> | long? |
AnyElement<decimal> | decimal |
AnyElement<decimal?> | decimal? |
AnyElement<double> | double |
AnyElement<double?> | double? |
AnyElement<float> | float |
AnyElement<float?> | float? |
Examples
Select Statement
Select the average of total purchase amount for all purchases (ignoring null values).
double avgSales = db.SelectOne(
db.fx.Avg(dbo.Purchase.TotalPurchaseAmount)
)
.From(dbo.Purchase)
.Execute();
Select Statement with Distinct
Select the average of distinct total purchase amount for all purchases (ignoring null values).
double avgSales = db.SelectOne(
db.fx.Avg(dbo.Purchase.TotalPurchaseAmount).Distinct()
)
.From(dbo.Purchase)
.Execute();
Order By Clause
Select the average of total purchase amount for all purchases (ignoring null values), grouped by payment method type and ordered by the average of total purchase amount descending.
IEnumerable<double> avgSales = db.SelectMany(
db.fx.Avg(dbo.Purchase.TotalPurchaseAmount)
)
.From(dbo.Purchase)
.OrderBy(db.fx.Avg(dbo.Purchase.TotalPurchaseAmount).Desc())
.Execute();
Having Clause
Select the average of total purchase amount for all purchases (ignoring null values), grouped by payment method type having an average greater than 10.
IEnumerable<double> avgSales = db.SelectMany(
db.fx.Avg(dbo.Purchase.TotalPurchaseAmount)
)
.From(dbo.Purchase)
.GroupBy(dbo.Purchase.PaymentMethodType)
.Having(db.fx.Avg(dbo.Purchase.TotalPurchaseAmount) > 10)
.Execute();