I have 2 tables
the first table table_new_data is like
date type data
2022-01 t1 0
2022-03 t2 1
2021-08 t1 1
the second table table_old_data is like
date type data
2021-10 t1 2
2022-04 t2 3
2021-07 t1 4
2021-06 t1 5
I'd like a sql code snippet that table_new_data LEFT JOIN table_old_data and produce the following result.
new_date type new_data old_date old_data
2022-01 t1 0 2021-10 2
2022-03 t2 1 null null
2021-08 t1 1 2021-07 4
Please note that,
- only join the rows with the same
type - for every row in
table_new_data, only join with a row intable_old_datathat has the closest previousdate. E.g., for2021-08 t1 1intable_new_data, we only want to join with2021-07 t1 4in thetable_old_data.
date is in YYYY-MM.
