Forum Discussion
List accumulate in groups
- 5 years ago
Hi Anonymous
Please see this example file for solution Grouped Running Total in PQ
Using a custom function and List.Generate you can create grouped running totals like this.
Custom Function fxGroupedRunningTotal
(values as list, grouping as list) as list => let GRTList = List.Generate ( ()=> [ GRT = values{0}, i = 0 ], each [i] < List.Count(values), each try if grouping{[i]} = grouping{[i] + 1} then [GRT = [GRT] + values{[i] + 1}, i = [i] + 1] else [GRT = values{[i] + 1}, i = [i] + 1] otherwise [i = [i] + 1] , each [GRT] ) in GRTListThis following query loads your data from a table and then calls the function, passing in the ID and Values columns.
let Source = Excel.CurrentWorkbook(){[Name="SourceData"]}[Content], BufferedValues = List.Buffer(Source[Value]), BufferedGroup = List.Buffer(Source[ID]), RT = Table.FromColumns( { Source[ID], Source[Index], Source[Value], fxGroupedRunningTotal(BufferedValues, BufferedGroup) }, { "ID", "Index", "Value", "Running Total" }) in RTPhil
If I answered your question please mark my post as the solution.
If my answer helped solve your problem, give it a kudos by clicking on the Thumbs Up.
Hello Anonymous
here maybe a straightforward solution
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("RczBDcAwCAPAXXinUoDSDhPl0Wb/HYppBA8/TrI9Bj3UiD2iNNtP8RxFBTl5Ft+9vXoytncytpbEVqtsEWjtJ+5JPEkRT+acHw==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, Index = _t, Value = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", type text}, {"Index", Int64.Type}, {"Value", Int64.Type}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"ID"}, {{"AllRows", (tbl)=> Table.AddColumn(tbl,"running total", (add)=> List.Sum(Table.SelectRows(tbl, each [Index]<= add[Index])[Value]))}}),
#"Expanded AllRows" = Table.ExpandTableColumn(#"Grouped Rows", "AllRows", {"Index", "Value", "running total"}, {"Index", "Value", "running total"})
in
#"Expanded AllRows"
Copy paste this code to the advanced editor in a new blank query to see how the solution works.
If this post helps or solves your problem, please mark it as solution (to help other users find useful content and to acknowledge the work of users that helped you)
Kudoes are nice too
Have fun
Jimmy