ALTER TABLE [STOR].[T_PATIENT_DRUG_DELIVERY] ADD [TotalApplicationCount] decimal(20, 6) NULL
GO

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

update stor.T_PATIENT_DRUG_DELIVERY set TotalApplicationCount = Amount where TotalApplicationCount is null