Let's say you have the table:
A |
---|
10 |
3 |
4 |
8 |
You want to add up successsively each line, and produce:
A | Sum |
---|---|
10 | 10 |
3 | 13 |
4 | 17 |
8 | 25 |
One way is to add an index column and add a custom column which takes into its input the actual result it is calculating. The code is the following:
let
Source = Excel.CurrentWorkbook(){[Name="Table"]}[Content],
Typed = Table.TransformColumnTypes(Source,{{"A", Int64.Type}}),
Indexed = Table.AddIndexColumn(Typed, "Index", 0, 1, Int64.Type),
AddSumColumn = Table.AddColumn(Indexed, "Sum",
each [A] + (if [Index]=0 then 0 else @AddSumColumn{[Index]-1}[Sum]))
in
AddSumColumn
One key point is the @AddSumColumn
where @
is
mandatory for each recursive definition.
This works because a structure (list, record, table) is a bunch of lazy evaluated cells and can contain a result based on the content of an other part of the same structure. But an error will be raised if the evaluation of a cell depends on the same cell. (ex a = @a +1)
A simpler example would be let Source = {42, @Source{0},@Source{1}}
which is evaluated as let Source = {42,42,42}