I have two tables, call them "monthlyStoreCount" and "weeklySales"
monthlyStoreCount
| date | storeCount |
|---|---|
| 2022-01-01 | 89 |
| 2022-02-01 | 94 |
| ... | ... |
weeklySales
| date | sales |
|---|---|
| 2021-12-31 | 66 |
| 2022-01-07 | 16 |
| 2022-01-14 | 147 |
| 2022-01-21 | 185 |
| 2022-01-28 | 145 |
| 2022-04-04 | 2572 |
| ... | ... |
I am looking to join these tables to get the "storeCount" and latest "sales" as of the dates in the monthlyStoreCount table.
Is there any performant way to do this join? With the data shown the desired output would be:
| date | storeCount | sales |
|---|---|---|
| 2022-01-01 | 89 | 66 |
| 2022-02-01 | 94 | 145 |
| ... | ... | ... |
UNTESTED:
Using: https://docs.snowflake.com/en/sql-reference/constructs/join-lateral.html as a primer...
"for each row in left_hand_table LHT: execute right_hand_subquery RHS using the values from the current row in the LHT"
Lateral allows us to execute the sub query for each record in the Monthly Store Count. So we get the MSC record whose date is >= ws date. ordered by weekly sales date descending and get the 1st record (the one closest to the monthly store count date which is equal to or before that date.)