# Aggregation

> Summarise grouped, tree and pivoted rows with built-in aggregation functions or your own, and read the results from the API.

Aggregation computes a value for every group row from the rows inside it: total revenue per region, average deal size per sales rep, the latest order date per customer. The same `aggFunc` setting drives group rows, the grand total row, parent rows in [tree data](https://docs.birchui.com/grid-pro/tree-data.md) and the cells of a [pivot](https://docs.birchui.com/grid-pro/pivoting.md).

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> Aggregation requires `AggregationModule` from `@birchui/grid-pro`, usually together with `RowGroupingModule`.

**Live demo: Row grouping with aggregation** (runs on the HTML version of this page). Source of `demos/grouping-aggregation.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { AggregationModule, RowGroupingModule } from '@birchui/grid-pro';
import {
  button,
  docsTheme,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Row grouping with aggregation', height: 500 };

const columns: ColumnDef<Order>[] = [
  { field: 'region', header: 'Region', rowGroup: true, rowGroupIndex: 0 },
  { field: 'country', header: 'Country', rowGroup: true, rowGroupIndex: 1 },
  { field: 'customer', header: 'Customer', width: 190 },
  { field: 'product', header: 'Product', width: 180 },
  { field: 'rep', header: 'Sales rep', width: 150 },
  { field: 'quantity', header: 'Units', type: 'number', width: 100, aggFunc: 'sum' },
  {
    id: 'revenue',
    header: 'Revenue',
    type: 'number',
    width: 130,
    valueGetter: revenueOf,
    format: formatCurrency,
    aggFunc: 'sum',
  },
  {
    id: 'avgOrder',
    header: 'Avg order',
    type: 'number',
    width: 120,
    valueGetter: revenueOf,
    format: formatCurrency,
    aggFunc: 'avg',
  },
  { field: 'id', header: 'Orders', width: 100, aggFunc: 'count' },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(5000, 21),
    getRowId: (order) => order.id,
    modules: [RowGroupingModule, AggregationModule],
    groupPanel: true,
    groupDefaultExpanded: 1,
    groupTotals: true,
    defaultColumn: { sortable: true },
    theme: docsTheme(),
    ariaLabel: 'Orders grouped by region and country',
  });
  toolbar.append(
    button('Expand all', () => grid.expandAll()),
    button('Collapse all', () => grid.collapseAll()),
    'Drag a header into the group panel to group by it.',
  );
  const describe = () => {
    const groups = grid.getDisplayRows().filter((row) => row.kind === 'group').length;
    status.textContent = `${groups.toLocaleString()} visible group rows over ${grid.getRows().length.toLocaleString()} orders.`;
  };
  const off = grid.on('modelUpdated', describe);
  describe();
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}
```

## Add an aggregation to a column

Set `aggFunc` on a column definition. Group rows then show the aggregate in that column.

```ts title="regional-sales.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import { RowGroupingModule, AggregationModule } from '@birchui/grid-pro';

interface Sale {
  id: string;
  region: string;
  rep: string;
  customer: string;
  closedOn: Date;
  units: number;
  revenue: number;
}

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });

const columns: ColumnDef<Sale>[] = [
  { field: 'region', rowGroup: true, hidden: true },
  { field: 'rep', header: 'Sales rep' },
  { field: 'customer', aggFunc: 'distinct', header: 'Customers' },
  { field: 'closedOn', type: 'date', aggFunc: 'max', header: 'Last close' },
  { field: 'units', type: 'number', aggFunc: 'sum' },
  { field: 'revenue', type: 'number', aggFunc: 'sum', format: (value) => (value == null ? '' : usd.format(Number(value))) },
];

createGrid(container, {
  columns,
  rows: sales,
  getRowId: (row) => row.id,
  modules: [RowGroupingModule, AggregationModule],
  groupTotals: true,
});
```

A column's `format` function is used for its aggregate cells too, so totals look like the values they summarise. On group and total rows the formatter is called with `row` set to `undefined`, and the value can be `null` when a group has no usable values, so write formatters that handle both.

An unknown function name is ignored with one console warning naming the column.

## Built-in functions

| Name | Result | Notes |
| --- | --- | --- |
| `sum` | Sum of the numeric values | Numeric strings such as `'12.5'` are counted; other values are skipped. Uses compensated summation, so totals of many decimal amounts do not drift. |
| `avg` | Mean of the numeric values | Divides by the number of numeric values, not by the number of rows. |
| `min` | Smallest value | Compares numbers numerically, dates by time and text alphabetically. |
| `max` | Largest value | Same comparison rules as `min`. |
| `count` | Number of non-empty values | Rows where the value is `null` or `undefined` are not counted. |
| `distinct` | Number of different non-empty values | Dates are compared by time. |
| `first` | First non-empty value in the group | Follows the group's current row order, so it depends on sorting. |
| `last` | Last non-empty value in the group | Same ordering rule as `first`. |

All built-in functions ignore `null` and `undefined`. A group in which no value qualifies gets `null` from `sum`, `avg`, `min`, `max`, `first` and `last`, and `0` from `count` and `distinct`.

> **Tip**
>
> `count` counts values, not rows. To count rows regardless of content, aggregate a column that is always filled, such as the id column, or use the child count that every group row already shows.

## Custom aggregation functions

Pass a function instead of a name. It receives the column's non-empty values for the group and the leaf rows themselves, and returns the aggregate.

```ts
type AggFunc = (values: unknown[], rows: readonly any[]) => unknown;
```

Having the rows makes calculations that span columns easy. A revenue-weighted margin:

```ts
const weightedMargin: AggFunc = (_values, rows: readonly Sale[]) => {
  let revenue = 0;
  let profit = 0;
  for (const sale of rows) {
    revenue += sale.revenue;
    profit += sale.revenue * sale.margin;
  }
  return revenue === 0 ? null : profit / revenue;
};

const columns: ColumnDef<Sale>[] = [
  { field: 'region', rowGroup: true },
  { field: 'revenue', type: 'number', aggFunc: 'sum' },
  {
    field: 'margin',
    type: 'number',
    aggFunc: weightedMargin,
    format: (value) => (value == null ? '' : `${(Number(value) * 100).toFixed(1)}%`),
  },
];
```

More examples you can drop in:

```ts
import type { AggFunc } from '@birchui/core';

const median: AggFunc = (values) => {
  const numbers = values.map(Number).filter(Number.isFinite).sort((a, b) => a - b);
  if (numbers.length === 0) return null;
  const middle = Math.floor(numbers.length / 2);
  return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2;
};

const range: AggFunc = (values) => {
  const numbers = values.map(Number).filter(Number.isFinite);
  return numbers.length ? Math.max(...numbers) - Math.min(...numbers) : null;
};

const listOfReps: AggFunc = (_values, rows) => [...new Set(rows.map((row) => row.rep))].sort().join(', ');
```

Keep custom functions pure and fast. They run for every group each time the data, filters or grouping change. If a function throws, the grid reports the error with `console.error`, leaves that aggregate empty and keeps rendering.

## Where aggregates appear

| Place | Rows aggregated |
| --- | --- |
| Group rows | Every data row under the group, at any depth. |
| Grand total row (`groupTotals: true`) | Every row that passes the current filters. Works with or without grouping. |
| Tree data parent rows | The leaf rows below the parent. The parent shows the aggregate in place of its own value. |
| Pivot cells | The rows that fall into that row group and pivot column. |
| Status bar | The cells in the current [range selection](https://docs.birchui.com/grid-pro/range-selection.md). The status bar computes its own sum, average, count, minimum and maximum, independent of `aggFunc`. See [Status bar](https://docs.birchui.com/grid-pro/status-bar.md). |

Aggregates always reflect the current filters. Filtering out a country lowers its region's total immediately.

## Read aggregates in code

Group and total display rows carry an `aggregates` object keyed by column id:

```ts
const regions = api
  .getAllDisplayRows()
  .filter((row) => row.kind === 'group' && row.depth === 0)
  .map((row) => ({ region: row.group?.label, revenue: row.aggregates?.revenue }));

console.table(regions);
```

To aggregate a whole column without grouping, for a KPI tile above the grid, use `getColumnAggregate(colId, aggFunc?)`. It aggregates the rows that pass the current filters, on every page, with the column's own `aggFunc` unless you pass another one, and falls back to `sum`. It is an optional member of `GridApi`, present while `AggregationModule` is installed:

```ts
const revenue = api.getColumnAggregate?.('revenue');
const activeCustomers = api.getColumnAggregate?.('customer', 'distinct');
```

The grid recalculates aggregates whenever rows change, so `modelUpdated` is a good moment to read them:

```ts
api.on('modelUpdated', () => {
  const total = api.getAllDisplayRows().find((row) => row.kind === 'total');
  document.querySelector('#revenue-total')!.textContent = String(total?.aggregates?.revenue ?? '');
});
```

## Editing and aggregates

When a user edits a cell, pastes into a range or drags the [fill handle](https://docs.birchui.com/grid-pro/fill-handle.md), the affected groups are recalculated. Aggregate cells on group rows are read-only; to change a total, edit the rows that make it up.

## Reference

- [`AggFuncName`](https://docs.birchui.com/api/core.md#aggfuncname) lists the built-in names.
- [`AggFunc`](https://docs.birchui.com/api/core.md#aggfunc) is the custom function signature.
- [`ColumnDef.aggFunc`](https://docs.birchui.com/api/core.md#columndef-aggfunc) is where you set it.
