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

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

    This is Oracle query but should work in any SQL. It is simplified and does not include all necessary calculations. You can add them yourself. You will see slightly diff totals as 17.50*3 not 17.50*1:

    SELECT po_sku AS sku, po_total, sale_total, (po_total-sale_total) Margin
      FROM
     (
      SELECT SUM(price*qty) po_total, sku po_sku
        FROM stack_test
      GROUP BY sku
     ) a,
     (
      SELECT SUM(price*qty) sale_total, sku sale_sku
        FROM stack_test_sale
       GROUP BY sku
     ) b
     WHERE po_sku = sale_sku
     /
    
    SKU     PO_TOTAL    SALE_TOTAL  MARGIN
    ---------------------------------------------------
    123     168.25      164         4.25
    456     420         80          340
    

    You can also add partition by SKU if required:

    SUM(price*qty) OVER (PARTITION BY sku ORDER BY sku)
    

提交回复
热议问题