Because a query is "live" meaning it can be sorted at any time and the calculation would need to be performed again, it is extremely inefficient to calculate a running sum in a query. However, it is a trivial and efficient process in a report since the report is a one pass through the data and you don't have to worry about sorting on the fly. Performing the calculation in a recordset loop is the same method used by the report engine. However, that implies that you are going to save the calculated results which is not at all recommended.
I am doing inventory access project, where user can trace back an item's data at any time in the past. I am trying to extract these info from ORDER and ORDERDETAIL table
For example, customer randomly desires to view the info of item A in Q2 (Mar/01 to June/31)
- ImportQty, Import_Amount,
- ExportQty, Export_Amount = ExportQty * everage_price
- Closing stock
- Closing Amount
- ....
Each import is probably with different quanity and price, so most challenge part is that
average_price calculation, it is the key factor and it changes all the time
1st: import qty n1, price p1 --> BalanceAmount= n1*p1; average_price1 = p1;
2nd: import qty n2, price p2 --> BalanceAmount= (n1*p1 + n2*p2); average_price2= BalanceAmount/ (n1 +n2);
3rd:
export qty n3 --> BalanceAmount= (n1*p1 + n2*p2) - (average_price2 * n3); average_price3 = BalanceAmount / (n1 +n2 - n3)
4rd: import qty n4, price p4 --> BalanceAmount= average_price3 *(n1 +n2 - n3) + n4*p4; average_price4 = BalanceAmount / (n1 +n2 - n3 + n4)
...so on
These value can be easily calculated and stoted in table at the time we do impoirt/export action
since they can be calculated, so I dont store them, but recalculating them in query looks exhausted.
These accumulative values also can be done with recordset loop, but i think query still faster and efficent