Simple Explanation
To get Totals and Subtotals directly from SOQL we can use
GROUP BY ROLLUP
let's take this sample data of Account
| BillingCountry | BillingCity | AnnualRevenue |
|---|---|---|
| USA | New York | 100,000 |
| USA | New York | 200,000 |
| USA | Boston | 150,000 |
| India | Chennai | 50,000 |
| India | Mumbai | 80,000 |
Use Case :
Let’s say we want to query the Billing Country and Billing City along with their respective Annual Revenues. We also need the totals for each country as well as the grand total across all countries.
SELECT BillingCountry, BillingCity, SUM(AnnualRevenue)
FROM Account
WHERE BillingCountry != NULL AND BillingCity != NULL
GROUP BY ROLLUP(BillingCountry, BillingCity)
ORDER BY BillingCountry, BillingCity
This will result in this
| BillingCountry | BillingCity | SUM(AnnualRevenue) | for illustration |
|---|---|---|---|
| India | Chennai | 50,000 | |
| India | Mumbai | 80,000 | |
| India | (null) | 130,000 | - Subtotal for India |
| USA | Boston | 150,000 | |
| USA | New York | 300,000 | |
| USA | (null) | 450,000 | - Subtotal for USA |
| (null) | (null) | 580,000 | - Grand Total |