首页 > 解决方案 > Sum with GroupBy in Nested Arrays in dataweave 2, Mule 4

问题描述

I would like to group by using the join_date and get the average qty (formulated by summing all in qty then divided by the number of records that have qty; do not take into account for those without qty).

Input

{
    "number": 282,
    "topic": [
        {
            "fruit": "apple",
            "colour": "red",
            "join_date": "today",
            "quality": [
                {
                    "date": "2020-08-21",
                    "in": {
                        "feedback": "good",
                        "qty": "3 qty"
                    },
                    "out": {
                        "feedback": "poor",
                        "qty": "1 qty"
                    }
                },
                {
                    "date": "2020-08-21",
                   "in" :{}
                },

                {
                    "date": "2020-08-22",
                    "in": {
                        "feedback": "normal",
                        "qty": "3 qty"
                    }
                } 

]},
{
            "fruit": "banana",
            "colour": "yellow",
            "join_date": "Yesterday",
            "quality": []
} ] }

Below is an example of intended output:

Output

number, fruit, colour, join_date, avginqty, avgoutqty
282, apple, red, today,  3 qty, 1 qty
282, banana, yellow, yesterday, ,

Thank you.

标签: muledataweavemulesoftmule4

解决方案


对于您提出的上一个问题有很多方法可以解决问题,这些方法应该让您有一个足够公平的想法来开始解决问题。对于您的问题、输入和预期输出,请在您尝试(DW 脚本)中发布解决问题以及您遇到相同问题的地方。

您还可以利用教程附带的Playground来帮助您更好地了解用法。

脚本

%dw 2.0
output application/csv
import * from dw::core::Arrays
---
flatten(payload.topic  groupBy $.join_date mapObject ((item) -> {
     temp: (if(sizeOf(item.quality)==0) [{}] else item.quality) default [{}] map {
     number: payload."number",
     fruit: item.fruit[0],
     colour: item.colour[0],    
     join_date: item."join_date"[0] default "",
     avginqty: ((($.in..qty) sumBy ($ splitBy " ")[0])/(($.in..qty) countBy ($ splitBy " ")[0] as Number  > -1)) ++ " qty" default " ",
     avgoutqty: ((($.out..qty) sumBy ($ splitBy " ")[0])/(($.out..qty) countBy ($ splitBy " ")[0] as Number  > -1)) ++ " qty" default " ",
     }
}) pluck $)

输出

number,fruit,colour,join_date,avginqty,avgoutqty
282,apple,red,today,3 qty,1 qty
282,banana,yellow,Yesterday, , 

推荐阅读