Search code examples
excelpowerbipowerquerypowerbi-desktopm

Group By Custom Function in M (PowerQuery)


I'm currently working on creating a custom function that takes three parameters:

  1. report
  2. field
  3. columnNewName

The aim of this function is to group the table report by the column labeled 'Appl Nbr' and then calculate the maximum value of the specified field, placing the result into a new column named columnNewName. I'd like to replicate this custom function into multiple tables: Image

However, I've encountered an issue with the following code snippet:

(report as table, field as text, columnNewName as text) =>

let
    Source = report,
    SelectedField = Table.SelectColumns(Source, field),
    #"Grouped Rows" = Table.Group(Source, {"Appl Nbr"}, {{columnNewName, each List.Max(SelectedField), type nullable number}})
in
    #"Grouped Rows"

Error 1 Error 2

If I replace the SelectedField with No. of Days, it works:

    (report as table, field as text, columnNewName as text) =>

let
    Source = report,
    SelectedField = Table.SelectColumns(Table1, "No. of Days"),
    #"Grouped Rows" = Table.Group(Source, {"Appl Nbr"}, {{columnNewName, each List.Max([No. of Days]), type nullable number}})
in
    #"Grouped Rows"

I attached the tables below:

Table1:

    let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjQwMFDSUTI0BRKheZklqSkKwSWJJanFQL5vZnJGYmqOQnByfkmJUqwOQjWYdCtKzEtOxa8OSLinFuUm5lUCWT6lKeWZ6QpOqaklGfllqXlQpaZwpegOQOVDVJuDXGqMzbloqmMB", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Appl Nbr" = _t, #"No. of Days" = _t, Country = _t, Name = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Appl Nbr", Int64.Type}, {"No. of Days", Int64.Type}, {"Country", type text}, {"Name", type text}})
in
    #"Changed Type"

Table 2

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjQwMFDSUTIC4tC8zJLUFIXgksSS1GIg3zczOSMxNUchODm/pEQpVgeu2BCI3YoS85JT8akyAWL31KLcxLxKIMunNKU8M13BKTW1JCO/LDVPKTYWAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Appl Nbr" = _t, #"No. of Weeks" = _t, Country = _t, Name = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Appl Nbr", Int64.Type}, {"No. of Weeks", Int64.Type}, {"Country", type text}, {"Name", type text}})
in
    #"Changed Type"

Solution

  • (report as table, field as text, columnNewName as text) =>
    
    let
        #"Grouped Rows" = Table.Group(report, {"Appl Nbr"}, {{columnNewName, (x)=> List.Max( Table.Column(x, field)), type nullable number}})
    in
        #"Grouped Rows"