Hi,
Please see the description below and accompanying screenshot.
I am looking for a complex multi-row IF formula:
Objective
When the purchase cost is NULL (i.e. for [TYPE] = "SALE") I want it to bring in the Purchase Cost of the first mathematically possible PURCHASE.
For example, in Records #1 and #2, I'd want the Purchase Cost from record #1 brought down into both cells. However, for record #9, I would like the Purchase Cost from record 4 brought down.
I'd like alteryx to recognise the first Purchase that the Sale could relate to i.e. the first sale of -72 (record #2) must be sold from the original purchase of 114 (record #1). Similarly, the second sale (-42 in record #3) has to come from the purchase of 114 (record #1). However, the sale of 75 (record #9) originates from the purchase of 171 units (record 4) NOT the purchase of 300 units (record #8).
If possible, I'd also like this to take account of the possible FUTURE scenario where I sell 300 units. I would need the purchase cost within the SALE row to display the sum of the purchase costs where the quantity sums to 200. i.e. it would need to factor in records #4, #5 and #6 (quantities 171, 2 and 35 respectively.

I have provided an Excel workbook which displays my ideal output (including the hypothetical sale).
Thank you so much in advance.
Jamie