Forum Discussion

Renato_mon's avatar
Renato_mon
Frequent Visitor
3 years ago
Solved

Group by with variable columns

Hi all,   I'd like to use group by to sum the values for several columns, but my database always changing the number of columns that was summarized. Amount is fixed, but the columns "xba-" is vari...
  • jennratten's avatar
    3 years ago

    Hello - this is how you can group and sum a variable number of columns... Included in the sample script below shows an example of how you can sum the values of all numeric data fields and another example of how you can sum the values of all fields beginning with "xba". 

    SCRIPT

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUTI2AhKGIMLMVClWByJoCsQW5kDCyAQhBhI0NwNpMYYLgvlGxkDCBKHb2ABqhKWFUmwsAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ColumnName1 = _t, #"xba-1" = _t, #"xba-2" = _t, #"xba-3" = _t]),
        ChangedType = Table.TransformColumnTypes(Source,{{"xba-1", Int64.Type}, {"xba-2", Int64.Type}, {"xba-3", Int64.Type}}),
        Grouped = Table.Group(ChangedType, {"ColumnName1"}, {{"Data", each _, type table }}),
        // Use this line to select all columns that are of type number.
        // ListOfColumnNames = Table.ColumnsOfType ( Grouped[Data]{0}, {type nullable number} ),
        // Use this line to select all columns beginning with xba.
        ListOfColumnNames = List.Select ( Table.ColumnNames ( Grouped[Data]{0} ), each Text.StartsWith ( _, "xba" ) ),
        SumGroupedData = Table.AddColumn ( 
            Grouped, 
            "SummedData", each 
            Table.FromRows ( 
                { 
                    List.Transform ( 
                        Table.ToColumns ( 
                            Table.SelectColumns ( [Data], ListOfColumnNames ) 
                        ), each try List.Sum ( _ ) otherwise _ 
                    ) 
                }, ListOfColumnNames 
            ) 
        ),
        Expand = Table.ExpandTableColumn(SumGroupedData, "SummedData", ListOfColumnNames)
    in
        Expand

    RESULT