sql >> Database teknologi >  >> RDS >> PostgreSQL

Beregning af den vægtede gennemsnitlige pris for produkternes lager

Du skal bruge rekursiv 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


  1. Begræns udenlandsk nøglerelation til rækker af relaterede undertyper

  2. PostGIS:Forespørgsel z og m dimensioner (linestringzm)

  3. Adgang nægtet; du har brug for (mindst én af) SUPER-rettighederne til denne handling

  4. Hvert GROUP BY-udtryk skal indeholde mindst én kolonne, der ikke er en ydre reference