Use Case
In one of my recent project, to achieve business objective I had to write a query to find total on the basis of certain criteria, say: GROUP BY Status, LeadSource. Further, I had to find subtotal on the basis of only Status. The solution which came on top of my mind was that get all records using a query something like: SELECT Status, LeadSource, COUNT(Name) cnt FROM Lead GROUP BY Status, LeadSource. And then loop through records and with the help of APEX, get the subtotals. As a developer, I can use collections to get my business objective. But I was curious to know if there is anything we can add in SOQL to get subtotals too.
Solution
My curiosity took me to "GROUP BY ROLLUP()" option.
With API version 18.0 and later, you can use GROUP BY ROLLUP to add subtotals for aggregated data in query results. This allows the query to calculate subtotals so you don't have to maintain that logic in your code. Use GROUP BY ROLLUP with aggregate functions, such as SUM() and COUNT(fieldName). The syntax is:
[GROUP BY ROLLUP (fieldName1[, fieldName2, fieldName3])]
A query with a GROUP BY ROLLUP clause returns the same aggregated data as an equivalent query with a GROUP BY clause. It also returns multiple levels of subtotal rows. You can include up to three fields in a comma-separated list in a GROUP BY ROLLUP clause.
The GROUP BY ROLLUP clause adds subtotals at different levels, aggregating from right to left through the list of grouping columns. The order of rollup fields is important. A query that includes three rollup fields returns the following rows for totals:
- First-level subtotals for each combination of fieldName1 and fieldName2. Results are grouped by fieldName3.
- Second-level subtotals for each value of fieldName1. Results are grouped by fieldName2 and fieldName3.
- One grand total row
For detailed example please see
Comments
Post a Comment