我试图计算我的利润,产品库存数量和价值,从购买和销售。假设我的购买表
还有我的销售表
目前,我已经使用php成功地完成了它。但由于我有超过10万购买和销售,它的工作非常缓慢。所以我需要一个mysql解决方案。下表描述了我的利润/库存计算方法。
所以我需要了解一下2017年11-23的报告
使用简单的选择查询或使用存储过程/函数来获得上述结果的快速工作方法是哪种?如果一个简单的查询更好,它应该是怎样的呢?
发布于 2017-11-26 11:27:17
到那时,您已经评论过每个Product_id
都需要结果,我几乎完成了在给定时间框架内显示Net Profit
、Stock Quantity
和Stock value
的解决方案。
因此,我在这里分享我的方法,因为它可能有助于您或其他人谁将试图解决这个问题。
解决方案:
select
final.profit,
final.Balance_Stock_Quantity,
final.Balance_Stock_Value
from
(
select tmp.date_,
tmp.`Sale/Purchase`,
tmp.product_id,
tmp.quantity,
tmp.rate,
tmp.val,
(
case when tmp.`Sale/Purchase` = 'purchase'
then (@total_quant := @total_quant + tmp.quantity)
else (@total_quant := @total_quant - tmp.quantity)
end
) as Balance_Stock_Quantity,
(
case when tmp.`Sale/Purchase` = 'purchase'
then (@total_val := @total_val + tmp.val)
else (@total_val := @total_val - (@total_rate*tmp.quantity))
end
) as Balance_Stock_Value,
(
case when tmp.`Sale/Purchase` = 'purchase'
then (@total_rate := @total_val/@total_quant)
else @total_rate
end
) as Balance_Stock_Rate,
(
case when tmp.`Sale/Purchase` = 'sale'
then (@profit := (tmp.rate - @total_rate)*tmp.quantity)
else @profit
end
) as profit
from
(
(select p_date as date_,
'Purchase' as `Sale/Purchase`,
p_product_id as product_id,
p_quantity as quantity,
p_rate as rate,
(p_quantity * p_rate) as val
from purchase
where p_date BETWEEN '2017-11-23 00:00:00' AND '2017-11-23 05:00:00'
)
union all
(select s_date as date_,
'Sale' as `Sale/Purchase`,
s_product_id as product_id,
s_quantity as quantity,
s_rate as rate,
(s_quantity * s_rate) as val
from sales
where s_date BETWEEN '2017-11-23 00:00:00' AND '2017-11-23 05:00:00'
)
)tmp
cross join
(select
@total_quant := 0,
@total_val := 0,
@total_rate := 0,
@profit := 0) r
order by tmp.date_
)final
order by final.date_ desc
limit 1
;
演示
注1: --我发现这是一个很有挑战性的问题,所以非常兴奋地开始解决这个问题,但最后我觉得我基本上在做一些编程语言已经做过的事情(例如,像case...when
这样的任务,以及使用变量来维护以前的Profit
、Quantity
等值)。
所以我真的不确定,这怎么会比你目前的方法更有效,但我想它仍然值得一试。
备注2:如果您的目标是显示每种产品的利润、股票和价值,我认为您应该坚持当前的方法。
尽管如此,如果您将Total quantity
、Rate
和Total value
存储在Purchase
和Sales
表本身的每个产品中(如您的问题中的第二张图片所示),您的任务就会变得容易。计算并存储这些值,同时在这些表中插入其他值,如果这些值是负担得起的。当您为最终报告编写查询时,这将节省大量时间和精力。
希望能帮上忙!
https://stackoverflow.com/questions/47493684
复制相似问题