Forum Discussion

borlip's avatar
borlip
Kudo Kingpin
11 years ago

Table.Group sum up dynamic columns

I have a pivoted table where each column represents revenue data by week starts. Week starts are column headers. There could be various number of columns.

 

I need to sum up each column (total revenue by week). I was thinking to use Table.Group

(table as table, key as any, aggregatedColumns as list, optional groupKind as nullable number, optional comparer as nullable function) as table

 

 

aggregatedColumns should be something like this: {{"1/7/2015", each List.Sum([1/7/2015]), type number}....

But how can I generate it on fly for a dynamic list of columns, as I don't know how many columns do I have?

2 Replies

  • borlip's avatar
    borlip
    Kudo Kingpin

    Got away without using Table.Group()... Unpivoted the table and grouped by dates to calculate sum of revenues per each date. Then pivoted the table by dates again...

  • Shahid12523's avatar
    Shahid12523
    Community Champion

    You can handle this in Power Query (M) by dynamically building the list of aggregation operations. Since your week-start columns are dynamic, you can’t hardcode them — you generate the list from the column names.

     

    Example in M:

    let
    Source = YourPivotedTable,
    ColNames = List.RemoveItems(Table.ColumnNames(Source), {"KeyColumn"}), // keep out keys
    AggList = List.Transform(ColNames, each {_, each List.Sum(_), type number}),
    Result = Table.Group(Source, {"KeyColumn"}, AggList)
    in
    Result


    Explanation:

    Table.ColumnNames(Source) → gets all column names.

    List.Transform → turns each into an aggregation spec {ColumnName, each List.Sum([ColumnName]), type number}.

    Table.Group → applies it dynamically.

    This way, no matter how many week columns you have, the grouping/summing will work.