[SalesForce] Why I can’t get the ID from group by along with Count(ID)

My goal is to get the ID and the COUNT(ID) [ie.expr0]. ? But i am struggling here! Any other way

  SELECT  COUNT(Id),Id, Application_Prefix__c FROM Test__c GROUP BY Application_Prefix__c  //ERROR Id should be group by

i tried

SELECT COUNT(Id),Id, Application_Prefix__c FROM Test__c GROUP BY Application_Prefix__c,Id //ERROR aggregate can't be used in group by

Best Answer

If you want to count how many records match each Application_Prefix__c, then you should remove Id from your SELECT clause:

SELECT COUNT(Id), Application_Prefix__c FROM Test__c GROUP BY Application_Prefix__c

You can't really get both the individual Id values and the count per prefix in a single query. If you wanted to get the counts using post-processing, you could do a Map<String, List<Test__c>> or even just a Map<String, Integer>. Here is a common grouping pattern:

List<Test__c> allRecords = [SELECT Application_Prefix__c FROM Test__c];
Map<String, List<Test__c>> prefixes = new Map<Id, List<Test__c>();
for (Test__c record : allRecords)
{
    if (!prefixes.containsKey(record.Application_Prefix__c))
        prefixes.put(record.Application_Prefix__c, new List<Test__c>());
    prefixes.get(record.Application_Prefix__c).add(record);
}
Related Topic