SOQL : Aggregate functions
Example : SELECT StageName, COUNT(Id), MIN(Amount), MAX(Amount), AVG(Amount) FROM Opportunity GROUP BY StageName
Here's a tabular overview of SOQL aggregate functions: | | |
| | |
| Aggregate Function | Description | Example Query |
| COUNT() | Counts the total number of records. | SELECT COUNT() FROM Account WHERE Industry = 'Technology' |
| COUNT(fieldName) | Counts non-null values in a specified field. | SELECT COUNT(Name) FROM Account WHERE Industry = 'Technology' |
| SUM(fieldName) | Calculates the total sum of a numeric field. | SELECT SUM(Amount) FROM Opportunity WHERE StageName = 'Closed Won' |
| AVG(fieldName) | Calculates the average of a numeric field. | SELECT AVG(Amount) FROM Opportunity WHERE StageName = 'Closed Won' |
| MIN(fieldName) | Returns the minimum value of a specified field. | SELECT MIN(CloseDate) FROM Opportunity WHERE StageName = 'Closed Won' |
| MAX(fieldName) | Returns the maximum value of a specified field. | SELECT MAX(CloseDate) FROM Opportunity WHERE StageName = 'Closed Won' |
| GROUP BY | Groups records based on the specified field. | SELECT Industry, COUNT(Id) FROM Account GROUP BY Industry |
| GROUP BY ROLLUP | Groups records with subtotals and grand totals for each group. | SELECT Industry, COUNT(Id) FROM Account GROUP BY ROLLUP(Industry) |
| HAVING | Filters grouped records based on aggregate values, used with GROUP BY. | SELECT Industry, COUNT(Id) FROM Account GROUP BY Industry HAVING COUNT(Id) > 10 |
| | |
| These functions allow for efficient and simplified data analysis directly within SOQL |
|
Using aggregate Functions in Apex Code// Without Aliases / Using Expressions
AggregateResult[] groupedResult = [SELECT StageName, MAX(Amount), MIN(Amount), AVG(Amount) FROM Opportunity GROUP BY StageName];
for(AggregateResult result: groupedResult){
System.debug('StageName: '+result.get('StageName')+' Max Amount: '+result.get('expr0')+' Min Amount: '+result.get('expr1')+' Avg Amount: '+result.get('expr2'));
}
// Using Aliases
AggregateResult[] groupedResult = [SELECT StageName, MAX(Amount) maxAmount, MIN(Amount) minAmount, AVG(Amount) avgAmount FROM Opportunity GROUP BY StageName];
for(AggregateResult result: groupedResult){
System.debug('StageName: '+result.get('StageName')+' Max Amount: '+result.get('maxAmount')+' Min Amount: '+result.get('minAmount')+' Avg Amount: '+result.get('avgAmount'));
}
Comments
Post a Comment