Sub topic 12
Adding subtotals with GROUP BY ROLLUP
This chapter assumes you can write a basic GROUP BY query, alias aggregate expressions, and read results from AggregateResult in Apex. It covers GROUP BY ROLLUP, which adds subtotal and grand total rows to a grouped query.
The problem ROLLUP solves
A plain GROUP BY returns one row per combination of the grouped fields. If you group leads by LeadSource and Rating, you get a count for each pair. To also show a count per source and an overall count, you would run extra queries, or add the numbers up in Apex.
GROUP BY ROLLUP returns all of those rows in one query.
Writing a ROLLUP query
Put the grouped fields inside ROLLUP(...):
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)The result contains three kinds of rows:
- Detail rows: one per
LeadSourceandRatingpair, as in a normalGROUP BY. - Subtotal rows: one per
LeadSource, withRatingset tonull. - A grand total row: one row with both
LeadSourceandRatingset tonull.
Suppose the leads are:
| LeadSource | Rating | Leads |
|---|---|---|
| Web | Hot | 4 |
| Web | Cold | 6 |
| Phone | Hot | 3 |
The query returns these rows:
| LeadSource | Rating | cnt |
|---|---|---|
| Web | Hot | 4 |
| Web | Cold | 6 |
| Web | null | 10 |
| Phone | Hot | 3 |
| Phone | null | 3 |
| null | null | 13 |
The row order is not guaranteed, so add ORDER BY if you need a fixed order.
Field order matters
ROLLUP works from right to left. It drops the last field first, then the next one, until none are left. So ROLLUP(LeadSource, Rating) gives subtotals per LeadSource and a grand total. It does not give subtotals per Rating.
If you need subtotals per Rating as well, reverse the field order in a second query, or use GROUP BY CUBE, which the next chapter covers.
Reading ROLLUP rows in Apex
In Apex, the subtotal rows come back as AggregateResult rows where the rolled-up fields are null. You can use that to label each row:
for (AggregateResult ar : [
SELECT LeadSource, Rating, COUNT(Id) cnt
FROM Lead
GROUP BY ROLLUP(LeadSource, Rating)
]) {
String source = (String) ar.get('LeadSource');
String rating = (String) ar.get('Rating');
Integer cnt = (Integer) ar.get('cnt');
String kind;
if (source == null && rating == null) {
kind = 'Grand total';
} else if (rating == null) {
kind = 'Subtotal for ' + source;
} else {
kind = 'Detail';
}
System.debug(kind + ': ' + cnt);
}Common errors
- Treating null as a subtotal marker. A lead can have a real
nullRating. That detail row looks the same as a subtotal row. TheGROUPINGfunction, covered in a later chapter, tells them apart. - Expecting subtotals for every field. ROLLUP only produces subtotals from right to left. Check the field order.
- Selecting a field that is not in the ROLLUP. Every non-aggregate field in
SELECTmust appear in theROLLUP(...)list. - Forgetting the aliases. Without an alias such as
cnt, Apex gets a generic name likeexpr0, which is easy to mix up.
Exercise
Exercise
You run SELECT StageName, Type, COUNT(Id) cnt FROM Opportunity GROUP BY ROLLUP(StageName, Type). Which subtotal rows does the result include, and how would you also get subtotals per Type?
Show answer
The result includes detail rows for each StageName and Type pair, subtotal rows per StageName (with Type null), and one grand total row (both null). It has no subtotals per Type, because ROLLUP drops fields from right to left. To get subtotals per Type, run a second query with ROLLUP(Type, StageName), or use GROUP BY CUBE(StageName, Type).