到那时,您已经评论说想要每个 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
;
DEMO
注意 1:我开始非常兴奋地解决这个问题,因为我发现这是一个具有挑战性的问题,但最后我觉得我基本上在做和你一样的事情已经用一些编程语言完成(例如,像case...when 这样的任务并使用变量来维护Profit、Quantity 等的previous值。
所以我真的不确定,这比你目前的方法效率如何,但我想它仍然值得一试。
注意 2:如果您的目标是显示每个产品的利润、股票和价值,我认为您应该坚持当前的方法。
不过,如果您将Total quantity、Rate 和Total value(显示在您的问题中的第二张图片中)为您的Purchase 和Sales 表本身中的每个产品存储,这将使您的任务变得容易。如果您负担得起,请计算并存储这些值,同时在这些表中插入其他值。当您为最终报告编写查询时,这将节省大量时间和精力。
希望对你有帮助!