Add column of previous values from table of tables in Power BI / Power Query

前端 未结 1 551
长发绾君心
长发绾君心 2021-01-25 03:11

Looking for a followup to Max Zelensky\'s solution here. Assuming the original example had a [Date] field, I\'m trying to go one more level and add a column that shows the prior

1条回答
  •  有刺的猬
    2021-01-25 03:59

    Similar to my answer here, instead of adding just one index, you can add two, one starting from 0 and one starting from 1, which we use to calculate the previous row by performing a self merge.

    let
        Source = Table.FromRows({{"A",#date(2019,1,1)},{"A",#date(2019,1,3)},{"B",#date(2019,1,2)},{"A",#date(2019,1,4)},{"B",#date(2019,1,5)}}, {"Name", "Date"}),
        ChangeTypes = Table.TransformColumnTypes(Source,{{"Name", type text}, {"Date", type date}}),
        GroupByName = Table.Group(ChangeTypes, {"Name"}, {{"tmp", each _, type table}}),
        AddIndices = Table.AddColumn(GroupByName, "Custom", each Table.AddIndexColumn(Table.AddIndexColumn([tmp],"Occurrence", 1,1),"Prev",0,1)),
        ExpandTables = Table.ExpandTableColumn(AddIndices, "Custom", {"Date", "Occurrence", "Prev"}, {"Date", "Occurrence", "Prev"}),
        SelfMerge = Table.NestedJoin(ExpandTables,{"Name", "Prev"},ExpandTables,{"Name", "Occurrence"},"Expanded Custom",JoinKind.LeftOuter),
        ExpandPriorDate = Table.ExpandTableColumn(SelfMerge, "Expanded Custom", {"Date"}, {"Prior Date"}),
        RemoveExtraColumns = Table.RemoveColumns(ExpandPriorDate,{"Prev", "tmp"})
    in
        RemoveExtraColumns
    

    0 讨论(0)
提交回复
热议问题