--select *
update pf
set pf.Amount = coalesce(p.Amount,1)
from PHARM.T_PRODUCT_FORM pf
outer apply(
	select top 1 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)
) p
--order by pf.BillOfGoods, pf.OrdinalNumber