In this context, querying fields without applying an aggregate function or grouping doesn't make much sense.
Let's say you have the following records:
Certification__c(ContactId = 1, version__c = 1, status__c = 'open')
Certification__c(ContactId = 1, version__c = 2, status__c = 'closed')
Certification__c(ContactId = 1, version__c = 2, status__c = 'closed')
Certification__c(ContactId = 1, version__c = 1, status__c = 'closed')
Certification__c(ContactId = 2, version__c = 2, status__c = 'closed')
Your query will group both of these records together into an AggregateResult
. If you don't use an aggregate function to choose the value of version__c
from one of those two records, and don't group by the values, which field value would be returned?
What if you wanted the field value for a different record in the result?
There isn't a way for a machine to make a decision one way or the other, which is why Salesforce is giving you that error.
Grouping by multiple fields gives you multiple AggregateResult
records. Something like
AggregateResult(ContactId = 1, version__c = 1, status = 'open')
AggregateResult(ContactId = 1, version__c = 1, status = 'closed')
AggregateResult(ContactId = 1, version__c = 2, status = 'closed')
AggregateResult(ContactId = 2, version__c = 1, status = 'closed')
which is based on the order that you specify fields in the GROUP BY
clause.
If you don't want to do that, then you might want to consider a parent-child subquery on Contact
with Certification__c
as the sub-query in the SELECT
clause.
This would give you a similar grouping, doing the heavy lifting of packaging the Certification__c
records based on which Contact
they belong to, while leaving you free to not group by other fields as well.
Of course, the drawback to that approach is that you can no longer use aggregate functions to, say, get the most recent date. You could overcome this particular example by additionally using ORDER BY Date_Received__c DESC
, but any other aggregate function you'd apply would need to be replicated in Apex.