SOQL Aggregate query: Count number of rows returned
Solution 1
Just counting records:
Integer counter = [ Select count()
FROM Payroll_Group_Detail__c
Where Tax_Batch__c = null
And CreatedDate >= 2012-07-21T00:00:00-05:00
And Total_Tax_Amount__c != null ];
System.debug('My counted records: ' + counter);
With a GROUP BY:
AggregateResult[] aggr = [ Select count(Id)
FROM Payroll_Group_Detail__c
Where Tax_Batch__c = null
And CreatedDate >= 2012-07-21T00:00:00-05:00
And Total_Tax_Amount__c != null
Group By Total_Tax_Amount__c ];
Integer counter = Integer.valueOf(aggr.size());
System.debug('#### counter: ' + counter);
But remember, you can not count more than the allowed governor limit (Total number of records retrieved by SOQL queries -> 50,000)
Solution 2
Grouping returns a row for each unique value in your grouping fields.
Salesforce Group By documentation
If all you want the total of Payroll_Group_Detail__c created after 7/21/12 where the Tax_Branch__c is blank but has Total_Tax_Amount__c set, just loose the Group By statement.
Solution 3
For any other poor souls like myself who are looking for help with this -- If you did not use an alias after the aggregate function, use this:
Object counter = aggr[0].get('expr0');
If you did use an alias after the aggregate function, you can use this:
Object counter = aggr[0].get('myalias');
See the docs: Working with SOQL Aggregate Functions
Richard N
I am a developer with over 6 years of software development experience across various platforms. Currently focusing on cloud technologies such as Salesforce and Workday. Have worked on the Force.com platform for about 3 years now. Love to work on APEX classes/triggers and Visualforce + SOQL. I am very interested in learning new technologies. I have recently started taking an active interest in learning and developing mashups using different technologies such as Google APIs, REST and SOAP API's along with Salesforce I currently hold the following Salesforce certifications Advanced Developer (passed the written exam. Waiting for the programming assignment) Advanced Administrator Developer Administrator Sales Cloud Consultant Service Cloud Consultant I have started to write about Salesforce in general at http://www.decodingthecloud.com/
Updated on October 11, 2020Comments
-
Richard N over 3 years
The following is my SOQL query:
select COUNT(Id) FROM Payroll_Group_Detail__c where Tax_Batch__c=null and CreatedDate >=2012-07-21T00:00:00-05:00 and Total_Tax_Amount__c!=null GROUP By Company__c,Name,Payment_Date__c,Pay_Cycle_Type__c;
I am was trying to count the number of rows returned by this group by clause. But instead of getting one count, I get multiple rows. How to get the overall count of rows returned by this grouping?
Thanks, Calvin