M – 将累计值(运行总计)转换为实际值

用户每月收到的月度销售总额(几万行)的客户报告。 销售额显示为运行总额,我试图find一个powerquery解决scheme来获得实际销售(*必填*)输出:

╔══════╦═══════╦═════════╦═══════╦════════════╗ ║ Year ║ Month ║ StoreID ║ Sales ║ *Required* ║ ╠══════╬═══════╬═════════╬═══════╬════════════╣ ║ 2017 ║ 10 ║ 1 ║ 5 ║ 5 ║ ║ 2017 ║ 11 ║ 1 ║ 11 ║ 6 ║ ║ 2017 ║ 12 ║ 1 ║ 18 ║ 7 ║ ║ 2017 ║ 11 ║ 2 ║ 10 ║ 10 ║ ╚══════╩═══════╩═════════╩═══════╩════════════╝ 

在tSQL中,我会做类似的事情

 Sales - LAG(Sales,1,0)OVER(Partiton by Year, StoreID Order by Month) 

一个类似的问题(但相反) 被回答 ,但提出的解决scheme看起来像一个交叉连接的等价物。 我是新来powerquery(所以我可能会误解),但我不能看到这是可行的,因为数据集每个月都在增长。 有没有更好的方法来处理这个问题,我在“M”中找不到一个例子?

编辑:List.Range看起来很有前途

实际上你需要当前行上一行的值。 一个常用的方法是添加2个索引列,一个以0开始,另一个以1开始。接下来,使用索引列作为联接列来合并表与索引列。 从嵌套表中展开所需列后,可以添加具有所需计算的自定义列。

 let Source = Sales, #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1), #"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1), #"Merged Queries" = Table.NestedJoin(#"Added Index1",{"Index"},#"Added Index1",{"Index.1"},"Previous",JoinKind.LeftOuter), #"Expanded Previous" = Table.ExpandTableColumn(#"Merged Queries", "Previous", {"StoreID", "Sales"}, {"Previous.StoreID", "Previous.Sales"}), #"Sorted Rows" = Table.Sort(#"Expanded Previous",{{"Index", Order.Ascending}}), #"Added Custom" = Table.AddColumn(#"Sorted Rows", "Required", each [Sales] - (if [StoreID] = [Previous.StoreID] then [Previous.Sales] else 0), Int64.Type), #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Index", "Index.1", "Previous.StoreID", "Previous.Sales"}) in #"Removed Columns"