Reference > Functions > Aggregate

Sum

  • 2005, 2008, 2012, 2014, 2016, 2017, 2019, 2022

Sum Aggregate Function

Use the Sum function to return the sum of a set of values.

Syntax

db.fx.Sum({expression})[.Distinct()]

Arguments

expression
The field expression, composite element, or function result to use in calculating the sum.
Distinct()
Return the summation of unique values only.

Returns

expression typereturn 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 sum of total purchase amount for all purchases.

double minSales = db.SelectOne(
        db.fx.Sum(dbo.Purchase.TotalPurchaseAmount)
    )
    .From(dbo.Purchase)
    .Execute();

Order By Clause

Select the sum of total purchase amount for all purchases ordered by the sum of total purchase amount descending.

IEnumerable<double> minSales = db.SelectMany(
        db.fx.Sum(dbo.Purchase.TotalPurchaseAmount)
    )
    .From(dbo.Purchase)
    .OrderBy(db.fx.Sum(dbo.Purchase.TotalPurchaseAmount).Desc())
    .Execute();

Having Clause

Select the sum of total purchase amount for all purchases (ignoring null values), grouped by payment method type having an sum greater than 10 and ordered by the sum of total purchase amount.

IEnumerable<double> minSales = db.SelectMany(
        db.fx.Sum(dbo.Purchase.TotalPurchaseAmount)
    )
    .From(dbo.Purchase)
    .GroupBy(dbo.Purchase.PaymentMethodType)
    .Having(db.fx.Sum(dbo.Purchase.TotalPurchaseAmount) > 10)
    .OrderBy(db.fx.Sum(dbo.Purchase.TotalPurchaseAmount))
    .Execute();
Previous
StDevP

© 2024 dbExpression. All rights reserved.