Sub topic 14
Aggregating filtered data with SUBTOTAL
Prerequisites
You should already know how to enter formulas in Google Sheets and how to identify cells and ranges, such as B2:B100. This chapter assumes you can apply a filter to a table.
A filter changes which rows are visible without deleting the data. A regular SUM still includes filtered-out rows. SUBTOTAL is an aggregate function designed for grouped or filtered data. It can calculate a total using only the rows that remain visible.
How `SUBTOTAL` works
The syntax is:
=SUBTOTAL(function_code, range1, [range2, ...])The function_code selects the calculation. For example, code 9 means SUM.
=SUBTOTAL(9, B2:B100)This formula adds the visible numeric values in B2:B100. Rows hidden by a filter are left out.
The following codes are useful for filtered tables:
| Code | Calculation | Example |
|---|---|---|
| 1 | Average | `=SUBTOTAL(1, B2:B100)` |
| 2 | Count numbers | `=SUBTOTAL(2, B2:B100)` |
| 3 | Count non-empty cells | `=SUBTOTAL(3, B2:B100)` |
| 4 | Maximum | `=SUBTOTAL(4, B2:B100)` |
| 5 | Minimum | `=SUBTOTAL(5, B2:B100)` |
| 9 | Sum | `=SUBTOTAL(9, B2:B100)` |
The range can include a header or other text. Text does not contribute to a sum, average, or numeric count.
Example: a filtered sales table
Suppose a sheet contains this table:
| A | B | C |
|---|---|---|
| Product | Sales | Region |
| Apples | 120 | East |
| Oranges | 85 | West |
| Apples | 150 | West |
| Pears | 90 | East |
Place this formula below the Sales column:
=SUBTOTAL(9, B2:B5)Before filtering, the result is 445. Now filter column C so that only East is visible. The formula recalculates using only the visible Apples and Pears rows, so the result becomes 210.
The calculation follows this pattern:
Multiple ranges and nested totals
SUBTOTAL accepts several ranges:
=SUBTOTAL(9, B2:B5, B8:B12)It adds visible values from both ranges. You can also use another supported function code, such as:
=SUBTOTAL(1, B2:B100)This returns the average of visible numeric cells.
SUBTOTAL ignores other SUBTOTAL formulas inside its referenced range. This prevents a grand total from adding section totals a second time. It does not automatically ignore an ordinary SUM formula, so avoid mixing regular totals into a range that contains a SUBTOTAL.
Use SUBTOTAL when the answer should change with a filter. Use SUM, AVERAGE, or COUNT when the calculation should include every row regardless of visibility.
Exercise
A filtered table has amounts in D2:D200. Which formula returns the sum of only the visible amounts?
Show answer
=SUBTOTAL(9, D2:D200)