Reference > Functions > Aggregate

Count

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

Use the Count function to return the number of items in a group of values.

Count Aggregate Function

Syntax

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

Arguments

expression
The value to count. If the parameter is not provided, a default of `*` will be used. When provided, must be of type `AnyElement`
Distinct()

Returns

int

Examples

Select Statement

Select the count of total purchase amount for all purchases.

int count = db.SelectOne(
        db.fx.Count(dbo.Purchase.TotalPurchaseAmount)
    )
    .From(dbo.Purchase)
    .Execute();

Order By Clause

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

int count = db.SelectOne(
        db.fx.Count(dbo.Purchase.TotalPurchaseAmount)
    )
    .From(dbo.Purchase)
    .OrderBy(db.fx.Count(dbo.Purchase.TotalPurchaseAmount).Desc())
    .Execute();

Having Clause

Select the count of all purchases, grouped by payment method type having an count greater than 10 .

IEnumerable<int> counts = db.SelectMany(
        db.fx.Count()
    )
    .From(dbo.Purchase)
    .GroupBy(dbo.Purchase.PaymentMethodType)
    .Having(db.fx.Count() > 10)
    .Execute();
Previous
Avg

© 2024 dbExpression. All rights reserved.