I have to calculate marginality for every single sales.
The problem is that not all sales are linked to cost, so i have created a second cost table with a created key that connect the single sales to every purchase done by subsidiary for a specific article.
I need to calculate an average cost of the last 10 days before sales. And in case in the last 10 days there's no purchase calculate an average cost of the last three purchases available before sale.
I use this function to calculate the 10 day average cost