Group By Rollup

AVAILABLE API VERSION
API v58.0 and later

The ROLLUP type adds subtotals for aggregate data in the query result. Use ROLLUP with aggregate functions, such as sum and count.

To aggregate results and include subtotals in the query result, use the following syntax. Replace objectApiName with the object's API name, like Account. Field1 and Field2 represent fields on the object, like Industry and AnnualRevenue.

A query that uses the groupBy argument with the ROLLUP type returns the same aggregated data as a query with the groupBy argument. However, a query with the ROLLUP type also returns multiple levels of subtotals. For example, you can return the number of records for each lead sources and a subtotal of those records using the ROLLUP type.

A query with the ROLLUP type can include up to three fields in a comma-separated list in the groupBy argument clause. The result includes one grand total regardless of how many rollup fields you use.

The order of rollup fields you pass in to the groupBy argument determines how the subtotals are calculated and how the results are grouped.

Grouping by one rollup field returns subtotals for each field selection and one grand total. For example, if you query the rollup by LeadSource, the query returns the number of records for each lead source and a grand total.

The previous query is similar to this SOQL statement.

A query that includes two rollup fields returns first-level subtotals for Field1. Results are grouped by Field2. For example, if you query the rollup by Status and LeadSource, the query returns subtotals for the number of records for each lead source that has a particular status.

The previous query is similar to this SOQL statement.

A query that includes three rollup fields returns:

  • First-level subtotals for each combination of Field1 and Field2. Results are grouped by Field3.
  • Second-level subtotals for each value of Field1. Results are grouped by Field2 and Field3.

SOQL and SOSL Reference: GROUP BY ROLLUP