For example I have the bellow table (tb_transaction)
id_trans date_trans production_plant dead_plant distribution_plant
25 2017-12-31 1000 100 200
26 2018-01-17 150 0 0
27 2018-02-07 0 50 100
28 2018-03-07 250 0 75
29 2018-05-10 500 50 0
Than I try to make a report table for this Year, like bellow table
month EarlyStock production dead LivePlant Distri EndStock
January 150 0 150 0 150
February 0 50 -50 100 -150
March 250 0 250 75 175
April 0 0 0 0 0
May 500 50 450 0 450
June 0 0 0 0 0
July 0 0 0 0 0
August 0 0 0 0 0
September 0 0 0 0 0
October 0 0 0 0 0
November 0 0 0 0 0
December 0 0 0 0 0
Which EarlyStock for January is EndStock December 2017 (assumed EarlyStock for December is 0) which is first data from tb_transaction than EarlyStock for February is EndStock January and so on.
My expected table is Than I try to make a report table for this Year, like bellow table
month EarlyStock production dead LivePlant Distri EndStock
January 700 150 0 850 0 850
February 850 0 50 800 100 700
March 700 250 0 950 75 875
April 875 0 0 875 0 875
May 875 500 50 1325 0 1325
June 0 0 0 0 0
July 0 0 0 0 0
August 0 0 0 0 0
September 0 0 0 0 0
October 0 0 0 0 0
November 0 0 0 0 0
December 0 0 0 0 0
Formula is:
- LivePlant = EarlyStock + production - dead
- EndStock = LivePlant - Distri
Any Sugestion how I can do it?
It looks like a Rolling Sum problem. It is doable in less verbose manner using Window Functions in MySQL 8.0.2 and onwards. But, since your MySQL version is 5.6, we can emulate this behavior using User-defined Session variables.
The basic gist of this technique is:
Where
to filter out row(s) from year(s), other than the current year.Try the following code (DB Fiddle DEMO):