diff --git a/force-app/main/default/classes/Q.cls b/force-app/main/default/classes/Q.cls index 96ccee4..a52a5f6 100644 --- a/force-app/main/default/classes/Q.cls +++ b/force-app/main/default/classes/Q.cls @@ -10,6 +10,7 @@ public class Q { private Integer numberOfRowsToSkip; private Set fieldList = new Set(); + private Set groupBy = new Set(); private List orders = new List(); private List conditions = new List(); private List subQueries = new List(); @@ -77,6 +78,22 @@ public class Q { return this; } + /** + * Add a GROUP BY statement + */ + public Q groupBy(String fieldName) { + this.groupBy.add(fieldName); + return this; + } + + /** + * Add a GROUP BY statement + */ + public Q groupBy(Set fieldNames) { + this.groupBy.addAll(fieldNames); + return this; + } + /** * Add a LIMIT statement */ @@ -125,6 +142,17 @@ public class Q { } } + /** + * Build the GROUP BY statement + */ + public String buildGroupBy() { + if (!this.groupBy.isEmpty()) { + return 'GROUP BY ' + String.join(new List(this.groupBy), ', '); + } else { + return null; + } + } + /** * Build the ORDER BY statement */ @@ -160,6 +188,10 @@ public class Q { queryParts.add(this.buildOrderBy()); } + if (!this.groupBy.isEmpty()) { + queryParts.add(this.buildGroupBy()); + } + if (this.numberOfRows != null) { queryParts.add('LIMIT ' + this.numberOfRows); } diff --git a/force-app/main/default/classes/QTest.cls b/force-app/main/default/classes/QTest.cls index b102c62..03ed6fb 100644 --- a/force-app/main/default/classes/QTest.cls +++ b/force-app/main/default/classes/QTest.cls @@ -105,4 +105,28 @@ private class QTest { Database.query(query); } + @isTest + static void testGroupBy() { + String query = + new Q(Lead.SObjectType) + .selectFields(new Set{'LeadSource', 'COUNT(Name)'}) + .groupBy('LeadSource') + .build(); + + System.assertEquals('SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource', query); + Database.query(query); + } + + @isTest + static void testGroupByMultiple() { + String query = + new Q(Lead.SObjectType) + .selectFields(new Set{'Status', 'LeadSource', 'COUNT(Name)'}) + .groupBy(new Set{'Status', 'LeadSource'}) + .build(); + + System.assertEquals('SELECT Status, LeadSource, COUNT(Name) FROM Lead GROUP BY Status, LeadSource', query); + Database.query(query); + } + } \ No newline at end of file