Forum Discussion

PhilippeMuniesa's avatar
PhilippeMuniesa
Icon for Resolver I rankResolver I
6 years ago
Solved

Dynamic Table.group

Hello,   I am a French user, and not find a lot of  documentation or examples in my language.   I'm looking to group (with sum agregation)  several columns of a table, by grouping with the Table....
  • Smauro's avatar
    Smauro
    6 years ago

    I'll try to break it down:

    List.Transform(List.Distinct(PreviousStep[CompteNum]), (t) => {Text.From(t), each List.Sum(Table.SelectRows(_, each [CompteNum] = t)[Montant]), type number})

    to

    List.Transform(
        List.Distinct(PreviousStep[CompteNum]),
        (t) =>
            {
                Text.From(t),
                each
                    List.Sum(
                        Table.SelectRows(
                            _,
                            each [CompteNum] = t
                        )
                            [Montant]
                    ),
                type number
            }
    )

    List.Transform takes two arguments: 1) a list and 2) a transformation function. Then, for each of its elements, it applies the transformation function.

    List.Distinct ( PreviousStep[CompteNum] ) gives a list of distinct elements in [CompteNum].

    (t) => ... is basically the transformation function defined. It takes one argument and returns a list in our case.


    I'll give an example:

    List.Transform(
        List.Transform({"a", "b"}, 
        (t) =>
            {
                Text.From(t),
                each
                    List.Sum(
                        Table.SelectRows(
                            _,
                            each [CompteNum] = t
                        )
                            [Montant]
                    ),
                type number
            }
    )​

    will return:

    {
        {
            "a",
            each
                List.Sum(
                    Table.SelectRows(
                        _,
                        each [CompteNum] = "a"
                    )
                        [Montant]
                ),
            type number
        },
        {
            "b",
            each
                List.Sum(
                    Table.SelectRows(
                        _,
                        each [CompteNum] = "b"
                    )
                        [Montant]
                ),
            type number
        }
    }


    Which is in turn passed as the third argument in Table.Group. I hope it already looks to you like Table.Group's third argument, which, when executed, every _ will be traslated as the grouped table based on the grouping criteria.

     

     

    Best,

    Spyros