update stor.T_PATIENT_DRUG_DELIVERY pd
set TotalApplicationCount = pdd.Amount * rr.Amount
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 JOIN LATERAL
(
	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.PatientDrugDeliveryID = pd.PatientDrugDeliveryID and pdd.Amount > 0 and ptCurr.OrdinalNumber != ptWoF.OrdinalNumber;