我正在Laravel 4中进行自我改进的库存管理项目,但无法找出执行平均月消费量(AMC)计算的最佳方法。
我有两个表,即商品表(id,item_name,price
)和存货卡(id, item_id, qty_in, qty_out,transaction_date
),我应该从中得出AMC计算。 / p>
FORMULA = (sum of current month's qty_out + sum of previous two month's qty_out) / 3
有人可以用纯PHP和mysql来帮助我解决问题吗?
答案 0 :(得分:2)
例如,您应该能够使用条件聚合来做到这一点
drop table if exists t;
create table t(item int,qty_out int , dt date);
insert into t values
(1,1,'2018-09-01'),(1,1,'2018-10-01'),(1,1,'2018-11-01');
select item,
sum(case when year(dt)*12 + month(dt) = year(now()) * 12 + month(now()) then qty_out else 0 end) thismm,
sum(case when year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -1) or
year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -2) then qty_out else 0 end) last2mm,
(sum(case when year(dt)*12 + month(dt) = year(now()) * 12 + month(now()) then qty_out else 0 end) +
sum(case when year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -1) or
year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -2) then qty_out else 0 end)
) / 3 amc
from t
where year(dt)*12 + month(dt) >= (year(now()) * 12 + month(now()) -2)
group by item ;
+------+-----------+-------+--------+
| item | thismonth | last2 | amc |
+------+-----------+-------+--------+
| 1 | 1 | 2 | 1.0000 |
+------+-----------+-------+--------+
1 row in set (0.01 sec)
请注意转换为月数,以简化日期在一年结束时的位置。 当然,如果您希望获得3个月的滚动平均值,那将是另一个问题。