计算平均每月消费

Calculating Average Monthly Consumption

我正在 Laravel 4 进行自我改进库存管理项目,但无法找出执行平均每月消耗 (AMC) 计算的最佳方法。

我有两个 table,即 commodities table (id,item_name,price) 和 stockcard (id, item_id, qty_in, qty_out,transaction_date) 我应该从中推导出 AMC 计算。

FORMULA = (sum of current month's qty_out + sum of previous two month's qty_out) / 3 

任何人都可以帮助我了解如何用简单的 PHP 和 mysql 解决这个问题吗?

例如,您应该能够使用条件聚合来做到这一点

   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 个月的滚动平均值,那将是一个不同的问题。