Forum Discussion
Fraze
4 years agoHelper I
Using previous row in current row calculation
Hello, trying to create an outstanding column using data from the previous row. See example below for situation. ID #1 has no previous data, so the outstanding balance is the Net change of $1...
- 4 years ago
Fraze can you try this
Column = SUMX ( FILTER ( 'Table', 'Table'[Date] <= EARLIER ( 'Table'[Date] ) && 'Table'[Customer] = EARLIER ( 'Table'[Customer] ) ), 'Table'[Net Change] )
ronrsnfld
4 years agoSuper User
It appears that you want to add a "running balance" column to each "group" of customers.
You can do that in M Code by Grouping, then using a custom aggregation to create the new subtable.
Please read the code comments for more detailed explanation:
let
Source = Excel.CurrentWorkbook(){[Name="Table35"]}[Content],
typeIt=Table.TransformColumnTypes(Source, {
{"Transaction ID", Int64.Type},{"Customer",Text.Type},{"Date",Date.Type},{"Net Change",Currency.Type}
}),
//Group by Customer
grp = Table.Group(typeIt,{"Customer"},{
//then add running balance column to each subtable
{"runningBalance", (t)=> Table.FromColumns(
Table.ToColumns(t) &
{List.Generate(
()=>[rb=t[Net Change]{0}, idx = 0],
each [idx]< Table.RowCount(t),
each [rb = [rb]+ t[Net Change]{[idx]+1}, idx = [idx]+1],
each [rb]
)})}}),
//Remove original customer table
//Then expand the grouped table
#"Removed Columns" = Table.RemoveColumns(grp,{"Customer"}),
#"Expanded runningBalance" = Table.ExpandTableColumn(#"Removed Columns", "runningBalance",
{"Column1", "Column2", "Column3", "Column4", "Column5"},
Table.ColumnNames(Source) & {"Outstanding"}),
//reset the data types
// could set up a more restricted environment than #shared if necessary
types = List.Transform(Table.Schema(typeIt)[TypeName] & {"Currency.Type"}, each Expression.Evaluate(_,#shared) ),
reType = Table.TransformColumnTypes(#"Expanded runningBalance",List.Zip({Table.ColumnNames(#"Expanded runningBalance"),types}))
in
reType