Grouped aggregation turns detailed rows into a summary at a chosen level of detail, or grain. The grouping keys define which rows belong together, and each aggregate specifies what to calculate from those rows. For example, grouping completed order line items by store and business date and summing their net amounts creates one sales total per store and date. Adding product category to the keys changes the grain and creates separate totals for each category. Unlike a windowed aggregate in SQL, a grouped aggregate does not preserve one output row per input row.
Filtering before grouping changes which rows contribute to the calculation. A SQL WHERE clause can exclude canceled orders before totals are computed, while HAVING can discard store-day groups whose resulting totals fall below a threshold. The order matters: excluding individual low-value orders is not the same as excluding groups with low total sales. In a DataFrame pipeline, the distinction is the same: an input filter runs before grouping and aggregation, while a filter on a computed total runs afterward.
Check the grain of the input before choosing a measure. On a table with one row per line item, COUNT(*) counts line items, not orders; counting distinct order IDs answers a different question. COUNT(column) skips null values, as do common measures such as SUM and AVG. A null grouping key, by contrast, can form a group. Ordinary grouping does not generate rows for dates with no matching records. To show zero-sales days in a report, join the summary to the expected store-date combinations and fill missing sales totals with zero where that interpretation is valid.
In cloud warehouses and distributed processing engines, workers can compute partial sums or counts locally and then merge them by key. Redistributing data by key, often called a shuffle, can become expensive when there are many distinct keys or when one key accounts for a disproportionate share of the data. Filter unneeded rows early, inspect the execution plan for large exchanges or spills, and check whether a few groups dominate processing time. Exact distinct counts can require substantially more data movement or memory than simple counts; use an approximate count only when the error is acceptable for the use case.
Frequently reused results can be written to a summary table to avoid scanning raw events for each dashboard query. That trades lower query cost and latency for storage, refresh work, and potential staleness. Keep measures that can be combined correctly at a coarser grain: for example, store both sum and non-null count to recompute an overall average rather than averaging group averages. For unbounded streams, grouping by key alone does not limit how much state the processor may need to retain. When the metric is defined over time, group by key and event-time window, then set a late-arrival policy that balances result completeness against state retention and reporting delay.