Calculating the Weighted Average Cost of products stock

前端 未结 5 1554
甜味超标
甜味超标 2020-12-28 23:12

I have to calculate my products stock cost, so for every product after each buy, i have to recalculate the Weighted Average Cost.

I got a view thats

5条回答
  •  盖世英雄少女心
    2020-12-29 00:00

    You need to use recursive CTE:

    SQLFiddle

    with recursive
    stock_temp as (
      select 
        *, 
        row_number() over(partition by product_id order by row_num) as rn
      from 
        stock_table 
    )
    
    ,cte as (
      select 
        document_type, document_date, 
        product_id, qty_out, qty_in, price, 
        row_num, stock_balance, rn, 
        price as wac
      from 
        stock_temp where document_type = 'SI'
    
      union all
    
      select 
        sub.document_type, sub.document_date,
        sub.product_id, sub.qty_out,  sub.qty_in, sub.price,
        sub.row_num, sub.stock_balance,  sub.rn,
        case when sub.qty_in = 0 then main.wac else 
        ((sub.stock_balance - sub.qty_in) * main.wac + sub.qty_in * sub.price) 
          / ((sub.stock_balance - sub.qty_in)  + sub.qty_in) end as wac
      from 
        cte as main
        join stock_temp as sub 
          on (main.product_id = sub.product_id and main.rn + 1 = sub.rn)
    )
    
    select * from cte
    

提交回复
热议问题