Aggregate query results
Summarize records with HOQS aggregate functions, group them, filter the groups, and bucket by time period.
Prerequisites
Section titled “Prerequisites”- You can already run a basic query — see Query and filter records.
1. Run a basic aggregate
Section titled “1. Run a basic aggregate”Every aggregate in SELECT needs an alias:
SELECT COUNT(*) AS total FROM core.Contact LIMIT 1SELECT SUM(amount) AS revenue, AVG(amount) AS avgDealFROM core.OpportunityLIMIT 12. Choose the right COUNT variant
Section titled “2. Choose the right COUNT variant”SELECT COUNT(*) AS total FROM core.Contact LIMIT 1SELECT COUNT(email) AS withEmail FROM core.Contact LIMIT 1SELECT COUNT(DISTINCT status) AS uniqueStatuses FROM core.Contact LIMIT 1COUNT(*) counts all rows. COUNT(field) counts non-null values. COUNT(DISTINCT field) counts unique non-null values.
3. Group results with GROUP BY
Section titled “3. Group results with GROUP BY”Non-aggregate fields in SELECT must appear in GROUP BY:
SELECT status, COUNT(*) AS nFROM core.ContactGROUP BY statusORDER BY n DESCLIMIT 1004. Filter groups with HAVING
Section titled “4. Filter groups with HAVING”WHERE filters individual rows before aggregation; HAVING filters groups after:
SELECT status, COUNT(*) AS nFROM core.ContactGROUP BY statusHAVING COUNT(*) > 10ORDER BY n DESCLIMIT 1005. Group by a time bucket
Section titled “5. Group by a time bucket”Time functions extract a date component for grouping, and work on Timestamp and Date fields:
SELECT YEAR(closedDate) AS yr, QUARTER(closedDate) AS qtr, SUM(amount) AS revenueFROM core.OpportunityGROUP BY YEAR(closedDate), QUARTER(closedDate)ORDER BY yr ASC, qtr ASCLIMIT 100Available functions: YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE.
Verification
Section titled “Verification”Confirm every non-aggregate field in your SELECT also appears in GROUP BY (otherwise the query is rejected with FIELD_NOT_IN_GROUP_BY), and that every aggregate expression carries an alias.
See also
Section titled “See also”- Querying Data with HOQS – why aggregates require an alias
- Query and filter records
- HOQS Query Language Reference – full aggregate and time function reference