I need to join price_bought from table products_purchased to a sales table, and then calculate the proper profit margin in the sales table.
SALES
| dt | product | qty | total |
|---|---|---|---|
| 2023-05-01 | X | 1 | 150 |
| 2023-05-01 | X | 2 | 300 |
| 2023-05-01 | Y | 1 | 100 |
| 2023-05-07 | X | 1 | 160 |
| 2023-05-07 | Y | 1 | 110 |
| 2023-05-07 | Y | 2 | 220 |
PRODUCTS_PURCHASED
| dt | product | price_bought |
|---|---|---|
| 2023-05-01 | X | 100 |
| 2023-05-01 | Y | 60 |
| 2023-05-07 | X | 110 |
| 2023-05-07 | Y | 66 |
What I expect:
SALES TABLE (output)
| dt | product | qty | total | price_bought |
|---|---|---|---|---|
| 2023-05-01 | X | 1 | 150 | 100 |
| 2023-05-01 | X | 2 | 300 | 100 |
| 2023-05-01 | Y | 1 | 100 | 60 |
| 2023-05-07 | X | 1 | 160 | 110 |
| 2023-05-07 | Y | 1 | 110 | 60 |
| 2023-05-07 | Y | 2 | 220 | 66 |
If there is always a price in
products_purchasedfor all dates when a product is sold, we can justjoin:Note that the join does not consider the quantity, as your data seems to show.
If, on the other hand, there may be sales dates without a corresponding product price, then:
you could just turn the
inner jointo aleft jointo avoid filtering out such rows (and get anullprice instead)or you might want to retrieve the latest price before that date ; one option uses a correlated subquery: