datetimepowerquerycustomcolumn

How to add custom column for previous day sales for each product in Power Query


I have this table:

Date Product Sales
1/3/2021 Apple 10
1/3/2021 Lemon 20
1/3/2021 Mango 30
1/4/2021 Apple 15
1/4/2021 Lemon 25
1/5/2021 Apple 20
1/5/2021 Lemon 20
1/5/2021 Mango 35

And I want to add a new column like this:

Date Product Sales Prev Day Sales
1/3/2021 Apple 10 null
1/3/2021 Lemon 20 null
1/3/2021 Mango 30 null
1/4/2021 Apple 15 10
1/4/2021 Lemon 25 20
1/5/2021 Apple 20 15
1/5/2021 Lemon 20 25
1/5/2021 Mango 35 null

Solution

  • You could add a column with previousDate and then join the table itself by Date-PreviousDate fields, then extract only the Sales field an rename it at wish.

    This should be null for days where no sales had taken place in the previous date.

    Add a custom column with previous date as Date.AddDays([Date],-1) Then, in Home/Transform/Merge queries and select the same table to merge. Select the "Previous Date" field from the original and merge with the "Date" field on the second. Then CTRL-Click the field "Product" to use it also in the merge. Use a left outer join, so no rows are added. Expand the Sales column in the merged result and, here you go! Greetings!