1

我有一个 JSON 数据,我需要对数据进行分组和求和。假设我有一个如下所示的 json 对象:

var dataString='[{"Company":"ABC","Focus":"Operate","Completed":"50","Remaining":"25"},{"Company":"ABC","Focus":"Operate","Completed":"20","Remaining":"50"},{"Company":"DEF","Focus":"Optimize","Completed":"100","Remaining":"75"},{"Company":"XYZ","Focus":"Innovate","Completed":"100","Remaining":"75"},{"Company":"ABC","Focus":"Improve","Completed":"50","Remaining":"50"},{"Company":"ABC","Focus":"Optimize","Completed":"50","Remaining":"25"},{"Company":"DEF","Focus":"Operate","Completed":"50","Remaining":"25"},{"Company":"ABC","Focus":"Improve","Completed":"50","Remaining":"25"},{"Company":"XYZ","Focus":"Operate","Completed":"50","Remaining":"25"},{"Company":"XYZ","Focus":"Operate","Completed":"50","Remaining":"25"},{"Company":"XYZ","Focus":"Optimize","Completed":"20","Remaining":"50"}]';

输出

output :: 数组内的数组,第一个数组应包含公司,然后再包含一个数组,该数组将包含我的焦点区域已完成数据和剩余数据的总和。

Company: 
   1. ABC --Focus -- 1.Operate  -- Completed :70 ,Remaining:75
                     2.Improve    -- Completed:100 ,Remaining:75
                     3.Optimize -- Completed:50 ,Remaining:25

   2. DEF--Focus-- 1.Operate  -- Completed:50 ,Remaining:25
                   2.Optimize -- Completed:100 ,Remaining:75  

   3. XYZ--Focus-- 1.Innovate  -- Completed:100 ,Remaining:75
                   2.Operate    -- Completed:100 ,Remaining:50
                   3.Optimize -- Completed:20 ,Remaining:50 

我已尝试以下查询来实现此目的:

  var resultxyz = Enumerable.From(dataString).GroupBy("$.Company", null,
    function (key, g) {
    var resultxyz = {
        z: key,
        totalCompleted: g.Sum("$.Completed"),
        totalRemaining: g.Sum("$.Remaining")

    }
    return resultxyz ;
}).ToArray();

但这只是对公司的分组,我也必须关注重点。任何想法或建议都会有很大帮助。

4

1 回答 1

1

基本上,您正在寻找一个两层分组。首先是所有公司的整体分组,以及在每个组内的焦点分组。有很多不同的方法可以建模,但最直接的方法是:

var query = Enumerable.From(data)
    .GroupBy("$.Company", null,
        function (key, g) {
            return {
                Company: key,
                Result: Enumerable.From(g)
                    .GroupBy("$.Focus", null,
                        "{ Focus: $, Completed: $$.Sum('Number($.Completed)'), Remaining: $$.Sum('Number($.Remaining)') }"
                    )
                    .ToArray()
            };
        }
    )
    .ToArray();

注意Number()函数的使用。由于CompletedandRemaining属性是字符串,因此求和不会像预期的那样工作。我们需要事先将它们转换为数字。

于 2015-12-14T21:51:03.737 回答