Forum Discussion

pedanticpad's avatar
pedanticpad
Helper II
6 years ago
Solved

Power Query - Join/Merge based on Date between 2 dates

Hi, I have two tables, a period table and a sales table.  I need to use the invoice creation timestamp on the sales table and assign the week number from the period table where the timestamp is between the timestamps.  Is there any way to join/merge the tables so I get my desired result below?

 

Thanks!

 

Period Table

 

Sales Table (Extract)

 

Desired Result (Sales Table with WeekPeriod)

8 Replies

  • mahoneypat's avatar
    mahoneypat
    Microsoft Employee

    You could do it in query but it is easier done in DAX.  Load both tables as is (with DateTime format for those columns), and use this expression in a calculated column on your Sales table.  This assumes there is no relationship between the Sales and Period tables.  If so, a small modification would be needed.

     

    WeekPeriod = var currenttime = Sales[Timestamp]

    return Calculate(min(Period[WeekNumber]), Period[WeekPeriod_StartTimeStamp]<=currenttime, Period[WeekPeriod_EndTimeStamp]>= currenttime)

     

    If this works for you, please mark it as solution.  Kudos are appreciated too.  Please let me know if not.

    Regards,

    Pat

      • edhans's avatar
        edhans
        Community Champion

        The following in M will do what you want.

         

            #"Added Custom" = 
                Table.AddColumn(#"Changed Type", "Some Number", each let
                        varDate = [Sales Date]
                    in
                        Table.SelectRows(Table, each [Date1] <= varDate and [Date2] >= varDate)[Some Number]{0}
                )

        You can see it in this PBIX file

         

        Note my data has some errors in the results because my Sales table has dates not in the Table date ranges. If you have the same issue you could wrap in a try/otherwise construct.

         

        If you want more help, please provide data per links below, not screenshots. Thanks!

        How to get good help fast. Help us help you.
        How to Get Your Question Answered Quickly
        How to provide sample data in the Power BI Forum