跳到内容
+

数据表格 - 聚合

向数据表格添加聚合功能,以便用户可以组合行值。

您可以通过打开列菜单并从聚合下的项目选择,通过数据表格界面聚合行。

聚合值将在数据表格底部的页脚行中呈现。

将聚合传递到数据表格

模型的结构

聚合模型是一个对象。键对应于列,值是要使用的聚合函数的名称。

初始化聚合

要在不控制其状态的情况下初始化聚合,请将模型提供给 initialState 属性。

Enter 开始编辑

受控聚合

使用 aggregationModel 属性来控制传递到数据表格的聚合。

使用 onAggregationModelChange 属性来监听聚合的更改并相应地更新属性。

Enter 开始编辑

禁用聚合

对于所有列

要禁用聚合,请将 disableAggregation 属性设置为 true。即使提供了模型,这也将禁用所有与聚合相关的功能。

对于某些列

要在特定列上禁用聚合,请将其列定义 (GridColDef) 上的 aggregable 属性设置为 false

在下面的示例中,年份列不可聚合,因为其 aggregable 属性设置为 false

以编程方式聚合不可聚合的列

要在不可聚合的列(在列定义aggregable: false 的列)上以编程方式应用聚合,您可以通过以下方式之一提供聚合模型

  1. aggregation.model 传递给 initialState 属性。这将使用提供的模型初始化聚合
  2. 提供 aggregationModel 属性。这将使用提供的模型控制聚合
  3. 调用 API 方法 setAggregationModel。这将使用提供的模型设置聚合。

在下面的演示中,尽管年份列不可聚合,但仍通过提供初始聚合模型以只读模式进行聚合。

与行分组一起使用

启用行分组后,聚合值将显示在两个位置

  1. 在分组行上——数据表格将在其分组行上显示每个组的聚合值。
  2. 在顶层页脚上——数据表格将添加一个顶层页脚来聚合所有行,就像处理平面行列表一样。

使用 getAggregationPosition 属性自定义此行为。此函数将当前组节点作为参数(根组为 null)并返回聚合值的位置。此位置必须是以下三个值之一

  1. "footer"—数据表格向组添加页脚以聚合其行。
  2. "inline"—数据表格禁用分组行上的聚合。
  3. null—数据表格不聚合组。
// Will aggregate the root group on the top-level footer and the other groups on their grouping row
// (default behavior)
getAggregationPosition=(groupNode) => (groupNode == null ? 'footer' : 'inline'),

// Will aggregate all the groups on their grouping row
// The root will not be aggregated
getAggregationPosition={(groupNode) => groupNode == null ? null : 'inline'}

// Will only aggregate the company groups on the grouping row
// Director groups and the root will not be aggregated
getAggregationPosition={(groupNode) => groupNode?.groupingField === 'company' ? 'inline' : null}

// Will only aggregate the company group "Universal Pictures" on the grouping row
getAggregationPosition={(groupNode) =>
(groupNode?.groupingField === 'company' &&
  groupNode?.groupingKey === 'Universal Pictures') ? 'inline' : null
}

// Will only aggregate the root group on the top-level footer
getAggregationPosition={(groupNode) => groupNode == null ? 'footer' : null}

下面的演示显示了每个组页脚上的 SUM 聚合,但没有显示在顶层页脚上

Enter 开始编辑

与树形数据一起使用

与行分组一样,您可以将聚合值显示在页脚或分组行中。

下面的演示显示了 大小 列上的 SUM 聚合和 最后修改时间 列上的 MAX 聚合

筛选

默认情况下,聚合仅使用筛选后的行。要使用所有行,请将 aggregationRowsScope 设置为 "all"

在下面的示例中,电影阿凡达未通过筛选器,但仍用于 总收入 列的 MAX 聚合

聚合函数

基本结构

聚合函数是一个对象,描述如何组合给定的值集。

const minAgg: GridAggregationFunction<number | Date> = {
  // Aggregates the `values` into a single value.
  apply: ({ values }) => Math.min(...values.filter((value) => value != null)),
  // This aggregation function is only compatible with numerical values.
  columnTypes: ['number'],
};

您可以在 GridAggregationFunction API 页面上找到完整的类型详细信息。

内置函数

@mui/x-data-grid-premium 包附带一组内置聚合函数,以涵盖基本用例

名称 行为 支持的列类型
sum 返回组中所有值的总和 number
avg 返回组中所有值的非四舍五入平均值 number
min 返回组中的最小值 numberdatedateTime
max 返回组中的最大值 numberdatedateTime
size 返回组中单元格的数量 all

移除内置函数

对于所有列

要从所有列中移除特定的聚合函数,请将过滤后的对象传递给 aggregationFunctions 属性。在下面的示例中,SUM 函数已被移除

Enter 开始编辑

对于一列

要限制给定列中的聚合选项,请将 availableAggregationFunctions 属性传递给列定义。

这使您可以指定哪些选项可用,如下所示

const column = {
  field: 'year',
  type: 'number',
  availableAggregationFunctions: ['max', 'min'],
};

在下面的示例中,您可以使用 MAXMIN 函数聚合 年份 列,而所有函数都可用于 总收入

Enter 开始编辑

创建自定义函数

将自定义聚合函数传递给 aggregationFunctions 属性。

聚合函数是一个具有以下形状的对象

const firstAlphabeticalAggregation: GridAggregationFunction<string, string | null> =
  {
    // The `apply` method takes the values to aggregate and returns the aggregated value
    apply: (params) => {
      if (params.values.length === 0) {
        return null;
      }

      const sortedValue = params.values.sort((a = '', b = '') => a.localeCompare(b));

      return sortedValue[0];
    },
    // The `label` property defines the label displayed in the column header when this aggregation is being used.
    label: 'firstAlphabetical',
    // The `types` property defines which type of columns can use this aggregation function.
    // Here, we only want to propose this aggregation function for `string` columns.
    // If not defined, aggregation will be available for all column types.
    columnTypes: ['string'],
  };

在下面的示例中,数据表格为 string 列添加了两个额外的自定义聚合函数:firstAlphabeticallastAlphabetical

聚合来自多个行字段的数据

默认情况下,聚合函数的 apply 方法接收一个值数组,该数组表示每行的单个字段值。例如,sum 聚合函数接收 gross 字段的值。

在下面的示例中,profit 列中的值派生自行的 grossbudget 字段

{
  field: 'profit',
  type: 'number',
  valueGetter: (value, row) => {
    if (!row.gross || !row.budget) {
      return null;
    }
    return (row.gross - row.budget) / row.budget;
  }
}

要聚合 profit 列,您必须分别计算 grossbudget 字段的总和,然后使用上面示例中的公式来计算聚合的 profit 值。

为此,请在聚合函数上使用 getCellValue 回调来转换传递给 apply 方法的数据

const profit: GridAggregationFunction<{ gross: number; budget: number }, number> = {
  label: 'profit',
  getCellValue: ({ row }) => ({ budget: row.budget, gross: row.gross }),
  apply: ({ values }) => {
    let budget = 0;
    let gross = 0;
    values.forEach((value) => {
      if (value) {
        gross += value.gross;
        budget += value.budget;
      }
    });
    return (gross - budget) / budget;
  },
  columnTypes: ['number'],
};

自定义值格式化器

默认情况下,聚合单元格使用其列的值格式化器。但是对于某些列,聚合值的格式可能需要与其他单元格值的格式不同。

为聚合函数提供 valueFormatter 方法以覆盖列的默认格式

const aggregationFunction: GridAggregationFunction = {
  apply: () => {
    /* */
  },
  valueFormatter: (params) => {
    /* format the aggregated value */
  },
};

自定义渲染

如果用于显示聚合的列具有 renderCell 属性,则聚合单元格会使用 params.aggregation 对象调用它,以让您决定如何渲染它。

此对象包含一个 hasCellUnit,可让您知道当前聚合是否具有与列的其余数据相同的单位——例如,如果列以 $ 为单位,则聚合值是否也以 $ 为单位?

在下面的示例中,您可以看到除了 size 之外,所有聚合函数都使用评级 UI 渲染,因为它不是有效的评级

签名
gridAggregationLookupSelector: (apiRef: GridApiRef) => GridAggregationLookup
// or
gridAggregationLookupSelector: (state: GridState, instanceId?: number) => GridAggregationLookup
示例
gridAggregationLookupSelector(apiRef)
// or
gridAggregationLookupSelector(state, apiRef.current.instanceId)
签名
gridAggregationModelSelector: (apiRef: GridApiRef) => GridAggregationModel
// or
gridAggregationModelSelector: (state: GridState, instanceId?: number) => GridAggregationModel
示例
gridAggregationModelSelector(apiRef)
// or
gridAggregationModelSelector(state, apiRef.current.instanceId)