Surely you want to update the row for vno 5, not 4? Assuming that's the case, you can get the output you want by changing the recursive with above:
- Changing row_number() => dense_rank () in the first subquery. This ensures rows for a particular VNO have the same rank, so the recursive search picks up both
- Adding start/end dates to the query. In the recursive branch, take the start/end value from the previous row if present
Example below.
The output will quickly get messy though and I'm not convinced it's correct in all cases. If you give us more background on what the business goal is here and why you're doing this we figure this out.
with rws as (
select d.*, m.vdate, m.vtype, d.effectif_date_start st, d.effectif_date_end en,
dense_rank () over (
order by m.vdate, m.vno
) rn
from stock_master m
join stock_detail d
on m.vno = d.vno
), stock (
vdate, st, en, item_code, qty, rate, amount,
qty_in_hand, avg_rate, avg_amount, vtype, rn
) as (
select vdate, st, en, item_code, qty, rate,
( qty * rate ) amount,
qty qty_in_hand,
( qty * rate ) / qty avg_rate,
( qty * rate ) avg_amount,
vtype,
rn
from rws
where rn = 1
union all
select r.vdate, nvl ( r.st, s.st ) st, nvl ( r.en, s.en ) en,
r.item_code, r.qty,
r.rate,
( r.qty * r.rate ) amount,
case
when r.vtype = 'PURCHASE' then
s.qty_in_hand + r.qty
else
s.qty_in_hand - r.qty
end qty_in_hand,
case
when r.vtype = 'PURCHASE' then
( s.avg_amount + ( r.qty * r.rate ) ) /
( s.qty_in_hand + r.qty )
else
s.avg_rate
end avg_rate,
case
when r.vtype = 'PURCHASE' then
s.avg_amount + ( r.qty * r.rate )
else
s.avg_amount - ( r.qty * s.avg_rate )
end avg_amount,
r.vtype,
r.rn
from stock s
join rws r
on s.rn + 1 = r.rn
)
select vdate, st, en, item_code, qty, rate
amount, qty_in_hand,
round ( avg_rate, 4 ) avg_rate,
round ( avg_amount, 4 ) avg_amount,
vtype
from stock;
VDATE ST EN ITEM_CODE QTY AMOUNT QTY_IN_HAND AVG_RATE AVG_AMOUNT VTYPE
25-JAN-0019 00:00:00 <null> <null> 001001 10 100 10 100 1000 PURCHASE
26-JAN-0019 00:00:00 <null> <null> 001001 50 150 60 141.6667 8500 PURCHASE
26-JAN-0019 00:00:00 <null> <null> 001001 15 160 45 141.6667 6375 SALE
27-JAN-0019 00:00:00 <null> <null> 001001 5 160 40 141.6667 5666.6667 SALE
28-JAN-0019 00:00:00 <null> 30-JAN-0019 00:00:00 001001 10 165 50 146.3333 7316.6667 PURCHASE
28-JAN-0019 00:00:00 30-JAN-0019 00:00:00 <null> 001001 12 165 52 147.0513 7646.6667 PURCHASE
28-JAN-0019 00:00:00 <null> 30-JAN-0019 00:00:00 001001 50 170 0 146.3333 0 SALE
28-JAN-0019 00:00:00 30-JAN-0019 00:00:00 <null> 001001 50 170 2 147.0513 294.1026 SALE