IgbPivotGrid の集計値には SUM・AVG・MIN・MAX・COUNT の組み込み集計関数が用意されていますが、これらにない集計(例: 中央値)を表示したい場合は、IgbPivotAggregator の AggregatorScript プロパティで JavaScript のカスタム集計関数を登録することで実現できます。
IgbPivotGrid の設定
まず、行と列に表示するディメンションを設定し、PivotConfiguration を IgbPivotGrid にバインドします。
<IgbPivotGrid Data="PivotSalesData"
Name="grid"
@ref="grid"
PivotConfiguration="PivotConfiguration1">
</IgbPivotGrid>
var pivotDimension1 = new IgbPivotDimension()
{
MemberName = "Country",
Enabled = true,
DisplayName = "国"
};
pivotConfiguration1.Columns = [pivotDimension1];
var pivotDimension2 = new IgbPivotDimension()
{
MemberName = "Product",
Enabled = true,
DisplayName = "製品"
};
pivotConfiguration1.Rows = [pivotDimension2];
AggregatorScript の使用
集計値の定義(IgbPivotValue)では、IgbPivotAggregator の AggregatorScript に、後述する JavaScript 側で登録した関数名を文字列で指定します。これを AggregateList に加えることで、SUM/AVG/COUNT と並ぶ集計方法の選択肢として UI 上に表示されます。
var pivotAggregator1 = new IgbPivotAggregator()
{
Key = "中央値",
Label = "中央値",
AggregatorScript = "MedianAggregatorScript"
};
IgbPivotValue pivotValue1 = new IgbPivotValue()
{
Member = "Sales",
DisplayName = "売上",
Enabled = true,
Aggregate = pivotAggregator1,
AggregateList = [
pivotAggregator1,
new IgbPivotAggregator() { Key = "合計", AggregatorName = PivotAggregationType.SUM, Label = "合計" },
new IgbPivotAggregator() { Key = "平均", AggregatorName = PivotAggregationType.AVG, Label = "平均" },
new IgbPivotAggregator() { Key = "件数", AggregatorName = PivotAggregationType.COUNT, Label = "件数" }
]
};
pivotConfiguration1.Values = [pivotValue1];
実際の集計処理は JavaScript 側で igRegisterScript を使って登録します。AggregatorScript に指定した文字列と、登録する関数名を一致させる必要があります。
igRegisterScript("MedianAggregatorScript", (members, data) => {
if (!data) {
return [];
}
const salesData = data.map(x => x.Sales);
return median(salesData);
}, false);
function median(numbers) {
if (!Array.isArray(numbers) || numbers.length === 0) {
throw new Error("数値の配列を指定してください。");
}
const sorted = [...numbers].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 1) {
return sorted[middle];
}
return (sorted[middle - 1] + sorted[middle]) / 2;
}
なお、AggregatorScript を使用したカスタム集計関数の登録は、現時点では Blazor WebAssembly でのみサポートされています。
実行結果
グリッドの集計方法の切り替え UI で「中央値」を選択すると、SUM/AVG/COUNT と同様に一覧に表示され、選択時には AggregatorScript で登録した関数によって算出された中央値が集計値として表示されます。
