[英]Accumulated formula in mysql
I have 3 tables in my database. 我的数据库中有3个表。 Here how it looks:
这里看起来如何:
tbl_production: tbl_production:
+--------+------------+-----+-------+
| id_pro | date | qty | stock |
+--------+------------+-----+-------+
| 1 | 2017-09-09 | 100 | 93 |
| 2 | 2017-09-10 | 100 | 100 |
tbl_out: 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: 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
前日期的累计库存+ tbl_production.qty-日期的SUM(tbl_out.qty)组+日期的SUM(tbl_return.qty)组
The stock of the date from 2017-09-09 is from 0 (because this is the first production) + 100 - 100 + 98 = 98 日期从2017-09-09开始的库存为0(因为这是第一批生产)+ 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 2017年9月10日起的库存为98(前几天的累积库存)+ 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. 在MySQL中,
GROUP BY
和变量并不总是能很好地协同工作。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.