Forum Discussion

asimpson22's avatar
asimpson22
New Member
3 years ago
Solved

Find closest date before transaction date based on unique ID

Hello!   I am a fairly new user to Power Query and am running into an issue. I have been asked to create an excel report where for all cancelled orders we include the previous sale date. From the m...
  • v-jingzhang's avatar
    v-jingzhang
    3 years ago

    Hi asimpson22 

     

    You may create a new query with below code. 

    let
        Source = Table.NestedJoin(CancelTable, {"SalesOffice", "Lot", "UniqueID"}, SalesTable, {"SalesOffice", "Lot", "UniqueID"}, "SalesTable", JoinKind.LeftOuter),
        #"Added Custom" = Table.AddColumn(Source, "Custom", each let __CancelDate = [CancelDate] in Table.FirstN(Table.Sort(Table.SelectRows([SalesTable], each [Sale Date] <= __CancelDate), {{"Sale Date", Order.Descending}}),1)),
        #"Removed Other Columns" = Table.SelectColumns(#"Added Custom",{"SalesOffice", "Lot", "UniqueID", "Transaction Type", "CancelDate", "Custom"}),
        #"Expanded Custom" = Table.ExpandTableColumn(#"Removed Other Columns", "Custom", {"Sale Date"}, {"Orig. Sale Date
    "})
    in
        #"Expanded Custom"

    Result:

     

    The problem is that from the current sample data, we cannot know which one is a record of a lot cancelling and then reselling on the same day, and which one is a record of a lot resold and then cancelled on the same day. There is no difference in the sample data. So you will find that for the example of Sales Office D, the output is not meeting your expected result. 

     

    I have attached a sample file at bottom. 

     

    Best Regards,
    Community Support Team _ Jing
    If this post helps, please Accept it as Solution to help other members find it. Highly appreciate your Kudos!