I would like to combine data between two datasets using FIFO. I think the warehouse principle is a good example to explain what I need.
BUY table:
ID_BUY | Date | Item | Count |
---|---|---|---|
39 | 2022-01-01 00:00 | Pencil | 1000 |
41 | 2022-02-02 00:00 | Pencil | 2000 |
44 | 2022-03-03 10:00 | Pencil | 3000 |
45 | 2022-03-03 12:00 | Pencil | 3500 |
47 | 2022-04-04 00:00 | Pencil | 4000 |
51 | 2022-05-05 00:00 | Glue | 5000 |
53 | 2022-06-06 00:00 | Book | 6000 |
SELL table:
ID_SELL | Date | Item | Count |
---|---|---|---|
40 | 2022-01-01 16:00 | Pencil | 1000 |
42 | 2022-02-02 17:00 | Pencil | 1200 |
43 | 2022-02-02 18:00 | Pencil | 800 |
46 | 2022-03-03 14:00 | Pencil | 6500 |
48 | 2022-04-04 15:00 | Pencil | 2100 |
49 | 2022-04-04 16:00 | Pencil | 1100 |
52 | 2022-05-05 20:00 | Glue | 2000 |
Expected data:
ID | ID_BUY | ID_SELL | Count |
---|---|---|---|
1 | 39 | 40 | 1000 |
2 | 41 | 42 | 1200 |
3 | 41 | 43 | 800 |
4 | 44 | 46 | 3000 |
5 | 45 | 46 | 3500 |
6 | 47 | 48 | 2100 |
7 | 47 | 49 | 1100 |
8 | 51 | 52 | 2000 |
Expected data description:
- Row ID = 1 --> 2022-01-01 I bought 1000 pencils and sold 1000 pencils few hours leter.
- Row ID = 2 and 3 --> 2022-02-02 I bought 2000 pencils and sold 1200 pencils to customer number 1 (ID = 2) and 800 pencils to customer number 2 (ID = 3).
- Row ID = 4 and 5 --> 2022-03-03 I bought 6500 pencils in two transactions (3000 and 3500) and sold them in one transaction (6500). In this case the limit in a row is determined by the buy transaction.
- Row ID = 6 and 7 --> 2022-04-04 I bought 4000 pencils and sold 3200 in two transactions (2100 + 1100). Now I have in stock 800 pencils (4000 - 3200 = 800) wating for next transaction(s). In this case the limit in a row is determined by the sell transaction.
- There are no books in the expected data as they were not sold.
I have tried to solve this problem with a cursor based on "SALES table". As I was doing this, I noticed that I had to use the cursor inside the cursor. The second cursor would have to be based on the "BUY table" plus what has not been settled from the expected data table, and in the next steps I would have to use IF. Maybe there is an easier way to solve this problem? CTE?