After being tasked with trying to improve the way my company keeps the fuel inventory, i hit a wall. My SQL knowledge is pretty basic and i don't even know where to start.
A little background: The company i work for own and operate 5 power plants which run on diesel. Our fuel stores operate based on FIFO, where the fuel we purchased first is spent first.
Before i started this project, the company did a lot of this manually in excel files, a whole bunch of different ones, which has led to large issues with inconsistency.
I envision one SQL table where each fuel transaction are recorded, which includes any purchases and transfers made. So far so good, but what im struggling with is trying to sum up how much fuel of various price "layers" are left at the various plants.
This is the setup i came up with for the transaction table as well as some sample data. Row id is a unique index while transaction id is not unique, and is a way to keep transfers between plants (where the same transaction means two rows, one for the source and one for the target).
row_id | transfer_id | date | type | plant | qty_in | qty_out | price |
---|---|---|---|---|---|---|---|
1 | 1 | 2022-05-01 | Purchase | plant_1 | 200 | 0 | 9000 |
2 | 2 | 2022-06-01 | Consumption | plant_1 | 0 | 100 | - |
3 | 3 | 2022-06-03 | Transfer | plant_1 | 0 | 50 | - |
4 | 3 | 2022-06-03 | Transfer | plant_2 | 50 | 0 | - |
5 | 4 | 2022-06-09 | Purchase | plant_1 | 150 | 0 | 5000 |
6 | 5 | 2022-07-15 | Purchase | plant_1 | 50 | 0 | 3000 |
7 | 6 | 2022-08-10 | Consumption | plant_1 | 0 | 150 | - |
The result i would like is something like this:
plant | qty | price |
---|---|---|
plant_1 | 50 | 5000 |
plant_1 | 50 | 3000 |
plant_2 | 50 | 9000 |
I hope i've managed to put into words what i am trying to achieve, and if its possible to implement. Lastly, i should also point out that i am not limited to any specific SQL server, but the ones we have been eyeing are MSSQL or MySQL simply because those are the ones i am aware of. If any of those is better suited, than that is what we will be using.
I have tried to implement the suggestion as found here but that gave me the wrong result as it depended heavily on the correct order of things in the table. It would subtract from the wrong price "layer", giving me the incorrect quantities.
<===EDIT===>
I tried implementing the answer from Lee Tom Here which works(ish). It gives me a inventory with the various price layers present, but it gives a wrong total_stock for the second layer. For plant_1 and product A it should be:
- 3 @ 30
- 1 @ 30
but i get:
- 3 @ 30
- 4 @ 30
I've created a fiddle with my attempt found here.