您如何将随时间累积的数字转换为 M(Power Query)中每个时间段的增量?

How do you turn an accumulating number over time into the delta per time period in M (Power Query)?

假设您有一个 table,其值为某个帐户代码,该帐户代码每三个月更新一次。但是,这个数额是逐年累积的,其中31-12的数据就是一整年,尽管也有过去三个季度的数据。现在我想将该列值转换为每季度的增量,而不是该日期之前的累计总数。所以第二季度就是第二季度的价值减去第一季度的价值。第三季度将是第三季度的值减去第二季度和一等。例如,我希望 31-12 的值为 517746,90 - 387949,44 = 129797,46。这将使对所有四个季度求和成为可能,并获得如果您只 select 四季度的值,您将看到的总和。在 M 中如何做到这一点?

示例:-

我做类似事情的方法是使用 List.Zip 创建一个 {current,prev} 列表的列表,然后将其转换为每对值之间的差异。然后您必须将该列表添加为新列。

查询 fAppendDeltaColumn

(Source as table, ColumnName as text) as table =>
let
    Values = Table.Column(Source, ColumnName),
    // All but the last value of Values, prepended with 0
    Prevs = List.Combine({
        {0},
        List.FirstN(
            Values,
            List.Count(Values) - 1
        )
    }),
    Deltas = List.Transform(
        List.Zip({Values, Prevs}),
        each _{0} - _{1}
    ),
    // So now we've got a list of delta values per row. Append it to the table.
    #"Appended Delta" = fAppendColumns(Source, {"Delta"}, {Deltas}, {type number})
in
    #"Appended Delta"

查询 fAppendColumns

这是我在想将值列表附加为新列时编写和使用的东西。我不相信这是一个 好的 方法。如果有更好的方法,请提前致歉。 :-)

  (table as table, NamePerColumn as list, ValuesPerColumn as list, optional TypePerColumn as nullable list) =>
let
    #"Added Index for fAppendColumns" = Table.AddIndexColumn(table, "IndexForAppendColumns", 0, 1),
    #"Added Columns" = List.Accumulate(
        List.Zip({NamePerColumn, ValuesPerColumn, if TypePerColumn = null then {} else TypePerColumn)}),
        #"Added Index for fAppendColumns",
        (table as table, NameValuesType as list) => let
            values = NameValuesType{1},
            #"Value Type" = if (TypePerColumn = null) then
                Value.Type(values{0})
            else
                NameValuesType{2}
        in
            Table.AddColumn(table, NameValuesType{0}, each values{[IndexForAppendColumns]}, #"Value Type")
    ),
    #"Removed Columns" = Table.RemoveColumns(#"Added Columns", {"IndexForAppendColumns"})
in
    #"Removed Columns"

从这里开始,只要没有任何拼写错误,您就可以执行以下操作:

let
    Source = YourTable,
    // make sure we're sorting by period
    #"Sorted Rows" = Table.Sort(Source, {{"Dim_period", Order.Ascending}}),
    // Assuming we want to get deltas per account. This creates one row per account, where "Subtable" is a column that contains all of the rows for that account, sorted by period thanks to the previous line.
    #"Grouped Rows" = Table.Group(#"Sorted Rows", {"ACCOUNT_CODE"}, {{"Subtable", each _, type table}}),
    #"Appended Deltas" = Table.TransformColumns(
        #"Grouped Rows",
        {"Subtable", each fAppendDeltaColumn(_, "Value")}
    ),
    #"Combined Subtables" = Table.Combine(#"Appended Deltas"[Subtable])
in
    #"Combined Subtables"