I have a table with charges and user id's and a separate table with plan changes. I need to join these tables in such a way that I know what the user's plan id was at the time of the charge in Snowflake.
Charge Table:
Charge_ID,User_ID,Inserted_At
AAAA ,1234 ,2022-01-01 15:00:00
AAAA ,1234 ,2022-02-01 15:00:00
BBBB ,5678 ,2022-01-05 18:00:00
BBBB ,5678 ,2022-02-07 18:00:00
Plan Table:
User_ID,Plan_ID,Inserted_At
1234 ,100 ,2022-01-01 13:00:00
1234 ,099 ,2022-01-01 14:00:00
1234 ,101 ,2022-01-18 13:00:00
5678 ,050 ,2022-01-04 13:00:00
5678 ,051 ,2022-02-08 13:00:00
Result:
Charge_ID,User_ID,Charge_Inserted_At ,Plan_ID
AAAA ,1234 ,2022-01-01 15:00:00 ,099
AAAA ,1234 ,2022-02-01 15:00:00 ,101
BBBB ,5678 ,2022-01-05 18:00:00 ,050
BBBB ,5678 ,2022-02-07 18:00:00 ,050
Do I need to cross join and lag, if so how can I accomplish that? Is there a way to accomplish this that's optimally efficient beyond some type of cross join?