Say I have purchase and sales data for some SKUs:
po_id | sku | purchase_date | price | qty
----------------------------------------------
1 | 123 | 2013-
This is really horrible since it changes a MySQL variable in the queries, but it kind of works (and takes 3 statements):
select
@income := sum(price*qty) as income,
@num_bought := cast(sum(qty) as unsigned) as units
from sale
where sku = 123
;
select
@expense := sum(expense) as expense,
sum(units) as units
from (select
price * least(@num_bought, qty) as expense,
least(@num_bought, qty) as units,
@num_bought := @num_bought - least(@num_bought, qty)
from purchase
where sku = 123 and @num_bought > 0
order by po_id
) as a
;
select round(@income - @expense, 2) as profit_margin;