Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
2 years ago
Solved

Help with creating a function, multiple SelectRows and GroupBy

Hi,   I need help with creating a function.    This is my sample data:   session_start session_user Daily_sum 9/20/2023 Person 1 4 9/22/2023 Person 1 5 9/25/2023 Person 1 8 ...
  • Anonymous's avatar
    Anonymous
    2 years ago

    Hi Anonymous ,

    let
      Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WstQ3MgAiI2MlHaWA1KLi/DwFQyDTRClWByxphEXSFCZpikXSAiZpjCZpBGQa49JphGysGRZJuIPMsUiaK8XGAgA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [session_start = _t, session_user = _t, Daily_sum = _t]),
        #"Changed column type" = Table.TransformColumnTypes(Source, {{"session_start", type date}, {"session_user", type text}, {"Daily_sum", Int64.Type}}),
    
      CustomFunction = (user as text, n as number) as table =>
        let
          FilteredRows = Table.SelectRows(#"Changed column type", each [session_user] = user and Date.IsInPreviousNDays([session_start], n)),
          GroupedRows = Table.Group(FilteredRows, {"session_user"}, {{"Sum", each List.Sum([Daily_sum]), type nullable number}}),
          Result = if List.Min(GroupedRows[Sum]) < 10 then Table.AddColumn(GroupedRows, "Final N Value", each n) else @CustomFunction(user, n-1)
        in
          Result,
    
      Users = List.Distinct(#"Changed column type"[session_user]),
      Results = List.Transform(Users, each CustomFunction(_, 10)),
      FinalResult = Table.Combine(Results)
    in
      FinalResult

    Output:

    If I've misunderstood your question, feel free to contact me.

     

    Best Regards,
    Gao

    Community Support Team

     

    If there is any post helps, then please consider Accept it as the solution  to help the other members find it more quickly.
    If I misunderstand your needs or you still have problems on it, please feel free to let us know. Thanks a lot!

    How to get your questions answered quickly --  How to provide sample data in the Power BI Forum