动态计算分组聚合

时间:2014-02-27 21:57:16

标签: javascript slickgrid

我有3列Total,Count和Each 每个=总数/计数;

使用slickgrid并总结每列是不​​正确的,因为加权平均值。

 Total     Count      Each
 4         2          2
 3         6          .5
---------------------------
 7         8          2.5 (incorrect )

7/8 = .875

 7         8          .875 (is correct if I take the sum(total) / sum(count) as an aggrigate)

我正在使用

new Slick.Data.Aggregators.Sum("Total")
new Slick.Data.Aggregators.Sum("Each")

但是我怎样才能获得那些2的总数并创建第3个聚合。

1 个答案:

答案 0 :(得分:1)

这个有点棘手,并且不常用于处理网格,但我设法将一些计算保存在全局变量中。

// global variables
var myGlobalCount = 0; 
var myGlobalTotal = 0;


function sumTotalsFormatter(totals, columnDef) {
    // keep the total inside the global variable 
    // this piece of code is new and outside of typical SlickGrid implementation
    switch(columnDef.field){
        case 'Count':   
            myGlobalCount = parseFloat(totals.sum[columnDef.field]);
            break;
         case 'Total':   
            myGlobalTotal = parseFloat(totals.sum[columnDef.field]);
            break;
    }

    // display as usual the Sum of whichever column that is
    // there is nothing new here, it's the simple SlickGrid sum display
    return '<span style="font-weight:bold;">'+totals.sum[columnDef.field]+'</span>';
}


function eachCalculation(totals, columnDef) {
    // VERY IMPORTANT.... The Each column has to come AFTER the other columns of Count & Total
    // the reason is simple we will use the global variables and they have to be filled prior to use them for calculation

    // do calculation with globale variables
    var eachTotal = myGlobalTotal / myGlobalCount;

    // display the calculation on the Title so that when you hover the total it will display calculation
    var titleText = "Total / Sum = " + eachTotal + " :: " + myGlobalTotal + " / " + myGlobalCount + " = " + eachTotal;

    return '<span style="font-size:9pt; font-weight:bold; color:gree" title="'+titleText+'">'+eachTotal+'</span>';
}

// Your columns definition will include your custom groupTotalsFormatter
columns1 = [
    {id:"Total", name:"Total", field:"Total", width:75, groupTotalsFormatter:sumTotalsFormatter},
    {id:"Count", name:"Count Part", field:"Count", width:100, groupTotalsFormatter:sumTotalsFormatter},
    {id:"Each", name:"Each", field:"Each", width:70, groupTotalsFormatter:eachCalculation}
];

我编辑了部分代码并且没有使用您的代码进行测试但它应该可以正常运行...尝试一下,让我知道您是否有问题...祝您好运