繁体   English   中英

如何按两个属性对 JSON 数据集进行分组并在 dataweave 中对值求和?

[英]How to group a JSON dataset by two properties and sum the value in dataweave?

我有一个数据集,我试图按两个单独的键进行分组,但嵌套了。 我曾尝试使用 groupBy 方法,但我很难计算键内的总和。

我也尝试过使用 pluck 方法,但使用嵌套的 groupBy 似乎也变得更具挑战性。 欢迎提出任何建议。 输入:

var sales =  [{
    "price": "500" as Number,
    "store": "123",
    "category": "1"
  },
  {
    "price": "400" as Number,
    "store": "123",
    "category": "2"
  },
  {
    "price": "700" as Number,
    "store": "123",
    "category": "2"
  },
  {
    "price": "800" as Number,
    "store": "456",
    "category": "6"
  },
  {
    "price": "900" as Number,
    "store": "456",
    "category": "7"
  },
  {
    "price": "400" as Number,
    "store": "456",
    "category": "6"
  }
  ]

Output:

 [
      {
        "123": {
            "1": {"price": "500"},
            "2": {"price": "1100"}
        }
        
      },
      {
        "456": {
            "6": {"price": "800"},
            "7": {"price": "1300"}
        }
        
      }
  ]

可能有一个最简单的方法。 我不明白为什么价格在输入和 output 中都存储为字符串而不是数字。它至少可以简化 output 以使用数字。

%dw 2.0
output application/json
var sales =  [{
    "price": "500" as Number,
    "store": "123",
    "category": "1"
  },
  {
    "price": "400" as Number,
    "store": "123",
    "category": "2"
  },
  {
    "price": "700" as Number,
    "store": "123",
    "category": "2"
  },
  {
    "price": "800" as Number,
    "store": "456",
    "category": "6"
  },
  {
    "price": "900" as Number,
    "store": "456",
    "category": "7"
  },
  {
    "price": "400" as Number,
    "store": "456",
    "category": "6"
  }
]
fun sumCategories(a)=
    a groupBy ($.category)
    mapObject ((value, key, index) -> {
        (key): 
            value reduce ((item, accumulator={ price: 0}) -> {price: item.price + accumulator.price} ) 
            mapObject {price: $ as String} // assumes single attribute
    })
---
sales 
    groupBy ($.store)
    mapObject ((value, key, index) -> (key): sumCategories(value))
    pluck {($$):$}

Output:

[
  {
    "123": {
      "1": {
        "price": "500"
      },
      "2": {
        "price": "1100"
      }
    }
  },
  {
    "456": {
      "6": {
        "price": "1200"
      },
      "7": {
        "price": "900"
      }
    }
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM