简体   繁体   中英

Accumulated formula in mysql

I have 3 tables in my database. Here how it looks:

tbl_production:

+--------+------------+-----+-------+  
| id_pro | date       | qty | stock | 
+--------+------------+-----+-------+  
| 1      | 2017-09-09 | 100 |  93   |
| 2      | 2017-09-10 | 100 |  100  |

tbl_out:

+--------+------------+-----+  
| id_out | date       | qty |  
+--------+------------+-----+
| 1      | 2017-09-09 | 50  |  
| 2      | 2017-09-09 | 50  |  
| 3      | 2017-09-10 | 50  |  
| 4      | 2017-09-10 | 50  |

tbl_return:

+--------+------------+-----+  
| id_out | date       | qty |
+--------+------------+-----+
| 1      | 2017-09-09 | 48  |  
| 2      | 2017-09-09 | 50  |  
| 3      | 2017-09-10 | 60  |  
| 4      | 2017-09-10 | 35  |

I would like to get the result the stock of the day. This what the table should be:

+------------+------+  
| date       | sotd |
+------------+------+
| 2017-09-09 | 98   |  
| 2017-09-09 | 193  |

This result is from the

accumulated stock from the days before + tbl_production.qty - SUM(tbl_out.qty) GROUP by date + SUM(tbl_return.qty) GROUP by date

The stock of the date from 2017-09-09 is from 0 (because this is the first production) + 100 - 100 + 98 = 98
The stock of the date from 2017-09-10 is from 98 (accumulated stock from the days before) + 100 - 100 + 95 = 193

I already have the query something like this, but it can't be executed

SET @running_count := 0;
SELECT *,
       @running_count := @running_count + qty - (SELECT SUM(qty) FROM tbl_out GROUP BY date) + (SELECT SUM(qty) FROM tbl_return GROUP BY date) AS Counter 
FROM tbl_production
ORDER BY id_prod;

How can I get this result?

In MySQL, GROUP BY and variables don't always work well together. Try:

SELECT p.date,
       (@qty := @qty + qty) as running_qty
FROM (SELECT p.date, SUM(qty) as qty
      FROM tbl_production p
      GROUP BY p.date
     ) p CROSS JOIN
     (SELECT @qty := 0) params
ORDER BY p.date;

EDIT:

If you want the value from the day before , the expression is a bit complicated, but not hard:

SELECT p.date,
       (CASE WHEN (@save_qty := @qty) = NULL THEN -1  -- never happens
             WHEN (@qty := @qty + qty) = NULL THEN -1  -- never happens
             ELSE @save_qty
        END) as start_of_day
FROM (SELECT p.date, SUM(qty) as qty
      FROM tbl_production p
      GROUP BY p.date
     ) p CROSS JOIN
     (SELECT @qty := 0) params
ORDER BY p.date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM