Forum Discussion

Irisohyama6's avatar
Irisohyama6
Frequent Visitor
4 years ago
Solved

Moving Average

Hello all,   I am trying to get moving average for my data but I got stuck and wondering if any veteran know how to solve this.   Here are my dummy tables: Top left and right are the table...
  • v-yalanwu-msft's avatar
    4 years ago

    Hi, Irisohyama6 

    Since you are involved in iterative recursion, using DAX is not ideal. Power Query is recommended.
    Such as:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUXLLTM1JAdJ++UqxOhAhr9Ti4szkRCArMrUYIZqfhyYSnJuYk4Mk5gRku6QW5+bnpaCJolnihGGcExbjnFGMg2p1xjTNGauTneF2IClDsSIWAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Event = _t, Name = _t, Attendance = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Event", type text}, {"Name", type text}, {"Attendance", type text}}),
        #"Grouped Rows" = Table.Group(#"Changed Type", {"Event"}, {{"Seats", each Table.RowCount(_), Int64.Type}, {"a", each _, type table [Event=nullable text, Name=nullable text, Attendance=nullable text, #"Table (2).Target Occupation"=nullable number]}}),
        Custom1 = Table.AddColumn(#"Grouped Rows", "Atten", each Table.SelectRows([a], each ([Attendance] = "Yes"))),
        Custom2 = Table.AggregateTableColumn(#"Custom1", "Atten", {{"Event", List.Count, "Atten"}}),
        #"Added Custom" = Table.AddColumn(Custom2, "Occupation", each [Atten]/[Seats]),
        #"Merged Queries" = Table.NestedJoin(#"Added Custom", {"Event"}, #"Table (2)", {"Event"}, "Table (2)", JoinKind.LeftOuter),
        #"Expanded Table (2)" = Table.ExpandTableColumn(#"Merged Queries", "Table (2)", {"Target Occupation"}, {"Target Occupation"}),
        #"Changed Type1" = Table.TransformColumnTypes(#"Expanded Table (2)",{{"Occupation", Percentage.Type}}),
        #"Added Custom1" = Table.AddColumn(#"Changed Type1", "Target", each [Occupation]/[Target Occupation]),
        #"Added Index" = Table.AddIndexColumn(#"Added Custom1", "Index", 1, 1, Int64.Type),
        #"Added Custom3" = Table.AddColumn(#"Added Index", "Average", each List.Accumulate(
        List.FirstN( #"Added Index"[Target],[Index]
    ),List.First(  #"Added Index"[Target]),(x, y) => (x + y)/2)),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom3",{"Index"})
    in
        #"Removed Columns"

    The final output is shown below:

     


    Best Regards,
    Community Support Team _ Yalan Wu
    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.