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

前端 未结 4 1592
醉话见心
醉话见心 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:40

    Good question. The approach that I'm taking is to calculate the total sales. Then calculate cumulative purchases, and combine them with special logic to get the right arithmetic for the combination:

    select s.sku,
           (MarginPos - SUM(case when s.totalqty < p.cumeqty - p.qty then p.price * p.qty
                                 when s.totalqty between p.cumeqty - p.qty and p.qty
                                 then s.price * (s.totalqty - (p.cumeqty - p.qty))
                                 else 0
                            end)
           ) as Margin
    from (select s.sku, SUM(price*qty) as MarginPos, SUM(qty) as totalqty
          from sales s
         ) s left outer join
         (select p.*,
                 (select SUM(p.qty) from purchase p2 where p2.sku = p.sku and p2.sale_id <= p.sale_id
                 ) as cumeqty
          from purchase s
         )
         on s.sku = p.sku
    group by s.sku, MarginPos
    

    Note: I haven't tested this query so it might have syntax errors.

提交回复
热议问题