diff --git a/force-app/main/default/classes/SOQL.cls b/force-app/main/default/classes/SOQL.cls index 7ed6810..e9866c6 100644 --- a/force-app/main/default/classes/SOQL.cls +++ b/force-app/main/default/classes/SOQL.cls @@ -1119,7 +1119,9 @@ public virtual inherited sharing class SOQL implements Queryable { if (!groupedFields.isEmpty() || !aggregateFunctions.isEmpty()) { List selectFields = new List(); - removeNotGroupedFields(); + // To avoid "Field must be grouped or aggregated" error + // retain only grouped or aggregated fields + fields.retainAll(groupedFields); selectFields.addAll(fields); selectFields.addAll(aggregateFunctions); @@ -1129,15 +1131,6 @@ public virtual inherited sharing class SOQL implements Queryable { return 'SELECT ' + String.join(fields, ', '); } - - public void removeNotGroupedFields() { - // To avoid "Field must be grouped or aggregated" error - for (String field : fields) { - if (!groupedFields.contains(field)) { - fields.remove(field); - } - } - } } private class SoqlSubQuery implements SubQuery { diff --git a/force-app/main/default/classes/SOQL.cls-meta.xml b/force-app/main/default/classes/SOQL.cls-meta.xml index 651b172..998805a 100644 --- a/force-app/main/default/classes/SOQL.cls-meta.xml +++ b/force-app/main/default/classes/SOQL.cls-meta.xml @@ -1,5 +1,5 @@ - 61.0 + 62.0 Active diff --git a/force-app/main/default/classes/SOQL_Test.cls b/force-app/main/default/classes/SOQL_Test.cls index 3d9a31f..0a83674 100644 --- a/force-app/main/default/classes/SOQL_Test.cls +++ b/force-app/main/default/classes/SOQL_Test.cls @@ -1965,6 +1965,20 @@ private class SOQL_Test { Assert.areEqual('SELECT LeadSource FROM Lead GROUP BY LeadSource', soql); } + @IsTest + static void groupByWithDefaultFieldsAndAggregateFunction() { + // Test + String soql = SOQL.of(Lead.SObjectType) + .with(Lead.FirstName, Lead.LastName, Lead.Email) + .count(Lead.Name) + .with(Lead.LeadSource) + .groupBy(Lead.LeadSource) + .toString(); + + // Verify + Assert.areEqual('SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource', soql); + } + @IsTest static void havingFilterWithSObjectField() { // Test diff --git a/force-app/main/default/classes/SOQL_Test.cls-meta.xml b/force-app/main/default/classes/SOQL_Test.cls-meta.xml index 651b172..998805a 100644 --- a/force-app/main/default/classes/SOQL_Test.cls-meta.xml +++ b/force-app/main/default/classes/SOQL_Test.cls-meta.xml @@ -1,5 +1,5 @@ - 61.0 + 62.0 Active