--select *
update PHARM.T_PRODUCT_FORM main
set Amount = coalesce(p.Amount,1)
from PHARM.T_PRODUCT_FORM pf
left join lateral(
	select pff.Amount 
	from PHARM.T_PRODUCT_FORM pff 
	where pff.OrdinalNumber > pf.OrdinalNumber
	and pff.ProductFormID <> pf.ProductFormID
	and pff.BillOfGoods = pf.BillOfGoods
	and not exists(
				select * 
				from PHARM.T_PRODUCT_FORM ppp 
				where ppp.ProductFormID <> pff.ProductFormID 
					and ppp.BillOfGoods = pf.BillOfGoods 
					and ppp.OrdinalNumber > pf.OrdinalNumber
					and ppp.OrdinalNumber < pff.OrdinalNumber)
     limit 1
) p on true
where main.ProductFormID = pf.ProductFormID;
--order by pf.BillOfGoods, pf.OrdinalNumber