Skip to content

How Pivot aggregates data

Local Pivot automatically uses hierarchical aggregation whenever its input, operations and layout support safe reuse. Eligible built-in aggregates accumulate facts into leaf states, then reuse those states to calculate parent groups and totals. This reduces repeated accumulation in reports with nested rows, columns and subtotals.

Configure your dimensions, measures and totals as usual. No aggregation strategy option is required:

import type { PivotConfig } from '@revolist/pivot';
const pivot: PivotConfig = {
rows: ['region', 'product'],
columns: ['year'],
columnCollapse: false, // Keep this layout eligible for child-state reuse.
dimensions: [
{ prop: 'region' },
{ prop: 'product' },
{ prop: 'year' },
{ prop: 'sales' },
],
values: [{ prop: 'sales', aggregator: 'sum' }],
totals: { subtotals: true, grandTotal: true },
};

Direct accumulation

Fallback

Accumulate source facts at each required grain.

Accumulate facts at each grainEach source fact contributes directly to its leaf aggregate, subtotal and grand total. Each destination receives facts in source order.Source facts10 · 20 · 30 · 40Leaf aggregatesA: 30 · B: 70Subtotal100Grand total100

Facts update each relevant destination in the original order.

Hierarchical

Automatic

Read facts into leaves, then merge states.

Reuse child aggregate statesFacts 10 and 20 build leaf A with sum 30 and count 2. Facts 30 and 40 build leaf B with sum 70 and count 2. Their states merge into a subtotal with sum 100 and count 4, then into the grand total. Parent calculations reuse statistics instead of revisiting each fact.Source facts10 · 20 · 30 · 40Leaf A statesum 30 · count 2Leaf B statesum 70 · count 2Subtotal statesum 100 · count 4Grand total statesum 100 · count 4merge

Parents combine statistics from disjoint children.

One simplified row hierarchy. Both paths use the same contributing facts. Pivot automatically reuses eligible child states and retains direct accumulation when needed. Displayed subtotal cells are never counted again as facts.

In the direct accumulation path, each destination receives its contributing facts in source order. Hierarchical aggregation first builds leaf statistics and then merges children into their ancestors. Each original contribution reaches its parent once; generated subtotal rows and columns are presentation outputs, not additional facts.

Pivot selects the execution path internally. Custom callbacks, independent group/total operations, and layouts or policies that cannot safely reuse these states retain their original calculation contract. Existing compact-summary optimizations remain available.

The current packed path runs in synchronous local controller/plugin execution without resource accounting, source/result filters or ranking. It supports up to four row dimensions, two column dimensions and eight built-in measures shown on columns, with columnCollapse: false. Custom row trees, per-level column settings, suppressed totals, calculations and field sorting/parsing use the existing paths. Source access must also pass scalar-input safety checks. Cooperative execution retains its existing aggregation path and scheduling.

Merge statistics, then calculate the result

Section titled “Merge statistics, then calculate the result”

A displayed cell can omit information its parent needs. Pivot retains the statistics required by eligible operations instead of treating every child cell as an interchangeable number.

OperationState that can be reusedParent calculation
sumChild sumsAdd the sums of disjoint children.
countChild occurrence countsAdd the contributing counts.
avgNumeric sum, eligible numeric count and mean stateCombine the statistics, then calculate the average at the parent grain.
min / maxEligible child extremaSelect the minimum or maximum under the same input policy.

For example, one child contains [10] and another contains [20, 20, 20]. Their displayed averages are 10 and 20. The correct parent average uses sum 70 / count 4 = 17.5. Averaging the two displayed averages would give 15 and assign the children equal weight despite different fact counts.

Counts also retain their declared meaning. Under the default callbacks, count counts source occurrences, while avg divides by the number of finite values after numeric normalization. On [10, undefined, 'invalid'], default COUNT is 3 and AVG is 10. The count used by AVG is 1. Default numeric coercion still treats null, false and empty strings as zero; hierarchical reuse does not change those rules. Explicit numeric/scalar operation policies can select different eligible inputs. See input policies and counts.

Independent operations keep their original fact scope

Section titled “Independent operations keep their original fact scope”

values[].summaries can select different local operations for leaves, groups and totals:

const values: PivotConfig['values'] = [
{
prop: 'sales',
aggregator: 'sum',
summaries: { group: 'avg', total: 'max' },
},
];

Suppose two leaves contain [10, 20] and [5]. Their leaf SUM results are 30 and 5. A group AVG over both leaves is 35 / 3, and a grand MAX is 20, the largest original sale. Averaging the displayed sums would incorrectly give 17.5; taking their maximum would incorrectly give 30.

These independent scope overrides retain the existing original-fact calculation path. Hierarchical reuse does not change their meaning or replace them with a calculation over displayed child totals.

JavaScript numbers use binary floating-point arithmetic. Addition can lose a small contribution when it is combined with a much larger value, so regrouping additions can change the result:

Calculation orderJavaScript result
(1e16 - 1e16) + 11
(1e16 + 1) - 1e160

The mathematical sum is 1 in both expressions. Either calculation order can be closer to a high-precision reference on a particular dataset; neither gives universally more accurate sums. Differences may be significant for cancellation-heavy data, even when every input is finite. Hierarchical aggregation does not promise compensated summation, decimal accounting arithmetic or arbitrary precision.

If a requested SUM becomes nonfinite while building or merging hierarchical states, Pivot discards that candidate and uses the direct calculation path. This preserves the existing overflow behavior; it does not make an unrepresentable result finite. AVG retains separate mean statistics so it need not divide an overflowing raw sum.

Use a high-precision reference and a tolerance appropriate to the measure when validating numerical accuracy. Test uneven group sizes, cancellation, large magnitudes, missing values and multiple hierarchy levels. A second grid’s floating-point result is a comparison point, not the correctness definition. Check previously accepted numerical results when upgrading reports that depend on exact floating-point reproducibility.

Existing configurations and saved reports do not require changes. Pivot now automatically reuses child statistics when eligible. Because floating-point addition is not associative, SUM and AVG can differ from results produced by earlier releases, especially for cancellation-heavy data. This is a numerical behavior change, not a change to the meaning of the aggregates.

If your workflow depends on exact historical results, validate it before upgrading. No calculation-order setting is exposed.

Custom aggregators keep their existing input and callback contract unless a supported composition explicitly supplies reusable statistics. A function named sum is not, by itself, permission to merge its outputs. Composable custom aggregates describes the pipeline contract and its input-timing requirements.

Hierarchical aggregation avoids accumulating every source occurrence independently at every eligible ancestor. The opportunity grows when many facts share leaves and a report has several levels of totals. Small reports, sparse leaves, source preparation, result materialization or a fallback path can limit the benefit.

When comparing releases, benchmark the same source, dimensions, measures, totals, filters and execution mode. Include the complete model build and the memory required for aggregate state. The improvement depends on the report and its eligibility for child-state reuse.

aggregationSemantics independently pins where a report may execute. Remote aggregation remains owned by the backend; local aggregation optimizations do not change the standard remote request contract or reconstruct server totals from loaded pages.

Aggregate values · Totals and subtotals · Configuration reference · Execution and limits.