powerquery

Subtraction of previous period after grouping in Power Query


I have 2 tables in power query which I would like to append. But before appending these 2 tables I would like to implement the following subtraction (based on the Code, Group, and Date in power query. How to get around with this ?

Code Group  Amount  Date       ExpectedColumn   GroupBy(datelast-dateprevious)
1001    A   1       15/10/2023  1-0             15/10/2023-15/09/2023*(Not exist for 1001 and A so it is 0)
1001    A   100     15/11/2023  100-1           15/11/2023-15/10/2023
1001    A   50      15/12/2023  50-100          15/12/2023-15/11/2023
1001    D   5       15/01/2024  5-0             15/01/2024 -15/12/2023*(Not exist for 1001 and D so it is 0)
1001    D   10      15/02/2024  10-5            15/02/2024-15/01/2024
1001    D   20      15/03/2024  20-10           15/03/2024-15/02/2024
1001    C   40      15/04/2024  40-0            15/04/2024-15/03/2024*(Not exist for 1001 and C so it is 0)
1001    C   80      15/05/2024  80-40           15/05/2024-15/04/2024
1001    C   55      15/06/2024  55-80           15/06/2024-15/05/2024
1002    B   60      15/02/2024  60-0            15/02/2024-15/01/2024*(Not exist for 1002 and B so it is 0)
1002    B   50      15/03/2024  50-60           15/03/2024-15/02/2024

Solution

  • try

    let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Grouped Rows" = Table.Group(Source, {"Code", "Group"}, {{"data", each let a=Table.AddIndexColumn(_ , "Index", 0, 1, Int64.Type) in Table.AddColumn(a, "Output", each try [Amount]- a{[Index]-1}[Amount] otherwise [Amount]), type table }}),
    #"Expanded data" = Table.ExpandTableColumn(#"Grouped Rows", "data", {"Date", "Output"}, {"Date", "Output"})
    in #"Expanded data"
    

    enter image description here