Using Combined Statistics Query in Apex

Combined Statistics Query in SOQL

In SOQL, we can use a series of functions to perform combined statistical queries. Their functions are similar to SUM(), COUNT() and other functions in standard SQL.

official documentation

Using Combined Statistics Queries in Apex

In Apex, we can get a series of results by calling SOQL statements that combine queries. In Apex, the AggregateResult class is dedicated to storing these results.

official documentation

It should be noted that each instance of the AggregateResult class is an SObject type and is read-only. When we use its members, we need to display conversion.

for example:

// 得到所有“机会”记录中“数额”字段的平均值
AggregateResult[] groupedResultsAverage = [SELECT AVG(Amount) avgAmount FROM Opportunity];
Decimal avgAmount = (Decimal) groupedResultsAverage[0].get('avgAmount');

// 得到所有“机会”记录中“数额”字段值大于100的“数额”总值,并根据“客户”字段分组合并查询
AggregateResult[] groupedResults = [SELECT AccountId, SUM(Amount) sumAmount FROM Opportunity WHERE Amount > 100 GROUP BY AccountId];
        
for (AggregateResult ar : groupedResults) {
    System.debug('AccountId is: ' + (Id) ar.get('AccountId'));
    System.debug('Sum is: ' + (Decimal) ar.get('sumAmount'));
}

Uniqueness of COUNT() in a query

When using the COUNT() function, one thing is special: it must be the only element in the query.

for example:

// 查询所有“客户”对象记录的总数
Integer countAccount = [SELECT COUNT() FROM Account];
System.debug('Count of Accounts is: ' + countAccount);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324940417&siteId=291194637
Recommended