Adaptable

#Aggregations

An aggregation summarizes the values of a column over a group of rows — their sum, their average, how many distinct values there are. In a table view, aggregations fill the group rows; in a pivot view, they fill the pivot cells.

This page documents how you can leverage aggregations in both grouped table views and pivot views, and also how you can create custom aggregation types — either in JavaScript or as AdaptableQL expressions.

#Aggregating a column

To aggregate a column, you can specify an aggregation property for it in the available columns entities and then use it in a grouped view. Each group row then shows the aggregated value of the rows in the group:

const state: AdaptableUserState = {
  globalEntities: {
    availableColumns: {
      salary: {
        field: 'salary',
        dataType: 'number',
        use sum aggregation
        aggregation: 'sum',
      },
    },
  },
  view: {
    currentViewId: 'default',

    views: [
      {
        id: 'default',
        label: 'Default',
        columnOrder: [
          'firstName',
          your salary column will default  the sum aggregation
          'salary',
        ],
        groupColumns: {
          'language-group': { groupBy: 'preferredLanguage', label: 'Language' },
        },
      },
    ],
  },
};

However, you won't know ahead of time the aggregation a user needs, and a user can update it at runtime. This is when the view will use columnOverrides to configure the aggregations.

const tableView: AdaptableTableView = {
  id: 'by-language',
  label: 'By language',
  groupColumns: {
    'language-group': { groupBy: 'preferredLanguage', label: 'Language' },
  },
  columnOverrides: {
    the id of the column to override
    salary: {
      can override multiple properties - here only `aggregation`
      aggregation: 'avg', // replaces the 'sum' of the column definition
    },
    country: { aggregation: 'distinct' },
    bonus: { aggregation: false }, // turns it off
  },
};
#
A sum per group

The view groups developers by language, and each group row shows the total salary of the group.

open
loading demo…
Note

Aggregated values are shown on group rows, so a table view without row grouping has no way of showing aggregations.

#Built-in aggregations

AggregationApplies toValue
sumnumber columnsThe total of the values
avgnumber columnsThe average of the values
min, maxnumber columnsThe smallest / largest value
countevery data typeThe number of rows in the group
distinctevery data typeThe number of distinct values in the group

sum, avg, min and max skip empty and non-numeric values, so an empty cell doesn't count as 0. distinct compares dates and arrays by value.

#Aggregations in table views

Group rows are aggregated at every level of the grouping: with rows grouped by region, then by product, both the region rows and the product rows show their own totals.

A column has one aggregation. To show two aggregations of the same data — say, the total and the average revenue — define a second column on the same field, with its own label and aggregation. Calculated columns are aggregated like any other column.

#
Aggregations in table views

The Regions and products view groups by region, then product, and shows:

  • the total units and revenue — set in the column definitions;
  • the average revenue — a second column on the revenue field;
  • the highest unit price — a calculated column, ROUND([revenue] / [units], 0);
  • the number of distinct quarters.

The Products, no unit totals view turns off the units aggregation and averages revenue instead of summing it. Switch views from the picker.

open
loading demo…

Columns with aggregatable: false aren't offered in the aggregation pickers of the UI; an aggregation set in code still applies.

#Aggregations in pivot views

A pivot view lists its aggregations in pivotAggregationColumns: each entry aggregates a column (columnId) with an aggregation, under an optional label. Every column group of the pivot — one per quarter, below — contains all the aggregation columns, in array order. The same column can be aggregated more than once:

pivotColumns: [{ columnId: 'quarter' }],
pivotAggregationColumns: [
  { columnId: 'units', aggregation: 'sum', label: 'Units' },
  { columnId: 'revenue', aggregation: 'sum', label: 'Revenue' },
  { columnId: 'revenue', aggregation: 'max', label: 'Top revenue' },
],
pivotGroupColumns: [
  { id: 'region-group', groupBy: 'region', label: 'Region' },
],

Pivot views ignore the aggregation of column definitions: only pivotAggregationColumns count. Without a label, the header is the column label followed by the aggregation label, like Revenue (Sum).

#
Aggregations in a pivot view

Units and revenue are summed for each region and quarter. Top revenue is the revenue of the best-selling product, from a second aggregation of the revenue column.

open
loading demo…

The total columns, which summarize each column group, are covered in Pivot views.

#Custom aggregations

When the built-in aggregations aren't enough, define your own aggregation types in globalEntities.aggregationTypes, keyed by id. Columns and pivot aggregation columns reference them by id, like the built-in ones — aggregation: 'weightedAvg'.

An aggregation type is written in one of two ways:

  • with a reducer — JavaScript functions that fold the rows of a group into a value;
  • with an expression — an aggregated AdaptableQL expression, evaluated over the rows of each group. Expressions are plain strings, so they can be stored, shared and edited like the rest of the state.

Both share these properties:

  • label — shown in the aggregation pickers and in the default header of pivot aggregation columns. Defaults to the id;
  • dataTypes — the data types of the columns the aggregation applies to. The UI only offers the aggregation for columns of those types. Omit it to allow every data type;
  • returnDataType — the data type of the aggregated value. Defaults to 'number'.

#With a reducer

A reducer type has:

  • initialValue — the accumulator each group starts with. Use a function to create a new object (an array, a Set, …) for every group;
  • reducer(accumulator, value, data) — called for every row of the group with the cell value of the aggregated column and the row data; returns the new accumulator;
  • done(accumulator, rows) — optional, called once per group after the last row; returns the aggregated value. Without it, the aggregated value is the accumulator.
globalEntities: {
  availableColumns: {
    units: {
      field: 'units',
      dataType: 'number',
      aggregation: 'range',
    },
  },
  aggregationTypes: {
    range: {
      label: 'Range',
      dataTypes: ['number'],
      initialValue: () => ({ min: Infinity, max: -Infinity }),
      reducer: (acc, value) => ({
        min: Math.min(acc.min, value),
        max: Math.max(acc.max, value),
      }),
      done: (acc) => acc.max - acc.min,
    },
  },
},
#
Custom aggregations with reducers

Two custom aggregation types:

  • Range (units) — the difference between the largest and smallest value in the group;
  • List (product) — the distinct values of a text column, joined. It applies to text columns and returns text.
open
loading demo…

#With an AdaptableQL expression

An expression type has an expression instead of the reducer functions — an aggregated expression, with the column in curly braces:

globalEntities: {
  availableColumns: {
    price: { field: 'price', dataType: 'number', aggregation: 'weightedAvg' },
  },
  aggregationTypes: {
    weightedAvg: {
      label: 'Weighted avg',
      dataTypes: ['number'],
      expression: 'AVG{$SCOPE, WEIGHT([units])}',
    },
  },
},

The expression is evaluated over the rows of each group, and its value is the aggregated value:

  • $SCOPE stands for the aggregated column, so one type works for any column: on the price column above, AVG{$SCOPE, WEIGHT([units])} reads AVG{[price], WEIGHT([units])}. Expressions can also reference columns by id, like [units];
  • every aggregation function and clause is available: MEDIAN{$SCOPE}, AVG{$SCOPE, WEIGHT([units])}, COUNT{$SCOPE WHERE [units] >= 60}, SUM{[revenue]} / SUM{[units]};
  • aggregations combine with the scalar functions and operators: ROUND(AVG{$SCOPE, WEIGHT([units])}, 2).

The expression must aggregate: a per-row expression like [price] * 2 has no single value for a group, so the group rows stay empty and a warning is logged.

#
Custom aggregations with AdaptableQL

Three expression types, used in a table view and in a pivot view:

  • Weighted avg — ROUND(AVG{$SCOPE, WEIGHT([units])}, 2): the average unit price, weighted by the units sold;
  • Median — MEDIAN{$SCOPE};
  • Big orders — COUNT{$SCOPE WHERE [units] >= 60}: the number of rows in the group with at least 60 units.

The Pivot by quarter view uses Weighted avg in its aggregation columns. Switch views from the picker.

open
loading demo…

#Where custom types apply

Custom types are offered next to the built-in ones in the aggregation pickers of the UI, for the columns whose data type is in dataTypes.

A view can also define aggregation types of its own, in privateEntities.aggregationTypes. They are only available in that view:

privateEntities: {
  aggregationTypes: {
    median: {
      label: 'Median',
      dataTypes: ['number'],
      expression: 'MEDIAN{$SCOPE}',
    },
  },
},
columnOverrides: {
  units: { aggregation: 'median' },
},
Note

Custom aggregation types run in the browser, over the rows of each group. With server-side data, the server aggregates the group rows.

#Overriding and removing aggregation types

The aggregation types of a view are resolved id by id, over three layers: the built-in types, then globalEntities.aggregationTypes, then the view's privateEntities.aggregationTypes. At each layer, the entry for an id is one of:

  • a partial override — only label, dataTypes or returnDataType. It changes those properties of the type with the same id from the layers below, and keeps its computation. sum: { label: 'Total' } is the built-in sum, renamed;
  • a full type — with a reducer or an expression. It replaces the computation of the type with the same id (a reducer never mixes with an expression), and keeps its label, dataTypes and returnDataType unless it sets them. With a new id, it adds a type;
  • false — removes the type with that id.
globalEntities: {
  aggregationTypes: {
    keeps the built-in sum, renamed
    sum: { label: 'Total' },
    keeps the built-in avg, also offered for date columns
    avg: { dataTypes: ['number', 'date'] },
  },
},

A removed type isn't offered in the aggregation pickers, and the columns that use it aren't aggregated: their group rows stay empty, and a warning naming the column, the aggregation and where it was removed is logged. Remove a type for every view in globalEntities, or for one view in its privateEntities:

const withRemoved: AdaptableUserState = {
  globalEntities: {
    aggregationTypes: {
      no view offers sum
      sum: false,
    },
  },
  view: {
    currentViewId: 'default',
    views: [
      { id: 'default', label: 'Default' },
      {
        id: 'no-count',
        label: 'No count',
        privateEntities: {
          aggregationTypes: {
            only this view loses count
            count: false,
          },
        },
      },
    ],
  },
};

The layers apply in order, so for one view:

  • a global sum: false removes sum from every view;
  • a global avg: { label: 'Mean' } and a private avg: { dataTypes: ['number', 'date'] } give the view the built-in average, labelled Mean, for number and date columns;
  • a global weightedAvg expression and a private weightedAvg: false make weighted average available in every view but that one;
  • after a global sum: false, a private partial override like sum: { label: 'Total' } has nothing to override: it is ignored, with a warning. A private full type — with a reducer or an expression — brings sum back in that view.

#Editing aggregations in the UI

Users change aggregations from the Aggregations page of the settings panel, which lists the aggregated columns of the current view and adds, changes or removes their aggregation. In a pivot view, the same page edits pivotAggregationColumns. In a table view, the column inspector on the Columns page also has an Aggregation picker, next to the column's Aggregatable switch.

Every aggregation picker ends with New AQL aggregation…, which opens an editor for a new expression type: its label, the aggregated expression — $SCOPE is the column the picker is for — and the data types it applies to. Once saved, the column uses it. The new type is saved in the view's privateEntities.aggregationTypes, or, with Available in all views checked, in globalEntities.aggregationTypes. The expression must aggregate: a per-row expression like [price] * 2 can't be saved.

The Custom aggregations list, at the bottom of the Aggregations page, shows the expression types of the current view — its own and the global ones — to edit or delete them. Columns that use a deleted type are no longer aggregated.

The editor is available standalone as Adaptable.UI.ViewAggregationsEditor. For custom UIs, the useColumnAggregations hook exposes the aggregatable columns, the configured aggregations, the aggregation types available for each column (getAggregationOptions) and setAggregation / setAggregations — writing to columnOverrides in table views and to pivotAggregationColumns in pivot views. The useAggregationTypes hook lists the expression types defined in state (customAggregationTypes), and saves or deletes them (saveAggregationType, deleteAggregationType), in the current view or in all views.

Aggregation changes made in the UI are saved in the view, and persisted with it.