update pdd
set  pdd.TotalApplicationCount = pdd.Amount * rr.Amount
--select pdd.Amount * rr.Amount, pdd.TotalApplicationCount
from stor.T_PATIENT_DRUG_DELIVERY pdd
join stor.T_REMAINS_LINK_PACKAGE_TYPE ptCurr on ptCurr.PackageType = pdd.PackageType and ptCurr.Remains = pdd.Remains and ptCurr.WriteOff <> 1
join stor.T_REMAINS_LINK_PACKAGE_TYPE ptWoF on ptWoF.WriteOff = 1 and ptWoF.Remains = pdd.Remains
cross apply
(
	select exp(SUM(log(abs(rlpt.Amount)))) as Amount
	from stor.T_REMAINS_LINK_PACKAGE_TYPE rlpt
	where rlpt.Amount > 1 and rlpt.Remains = pdd.Remains and rlpt.OrdinalNumber <= ptCurr.OrdinalNumber and rlpt.OrdinalNumber >= ptWoF.OrdinalNumber
	group by rlpt.remains
) rr
where pdd.Amount > 0 and ptCurr.OrdinalNumber != ptWoF.OrdinalNumber