Calculate Profit Based on First-In, First-Out Pricing

前端 未结 4 1585
醉话见心
醉话见心 2021-02-07 18:10

Say I have purchase and sales data for some SKUs:

po_id | sku | purchase_date    | price | qty
----------------------------------------------
    1 | 123 | 2013-         


        
4条回答
  •  隐瞒了意图╮
    2021-02-07 18:43

    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;
    

提交回复
热议问题