function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew KingAndrew King 

need to write trigger that compiles sum of number field on mulitiple order records, and updates sum with each existing order record edit

hello, I'd like to create a trigger that compiles the sum of a number field on all order records, and updates the sum with each subsequent edit of the existing field on a record.  We need a running sum of the number field on all orders, and it needs to update every time we edit the number field on existing orders.  Any suggestions on how to write this trigger.  

Example: we have number field A with a value of 10 on order 1.  we have number field A with a value of 20 on order 2.  The sum is 30.  we go back and edit the number field on order 2 from 20 to 30.  we need the sum to change from 30 to 40.  instead it is changing from 30 to 60.  we need it to replace the old value with the new, not add the new value to the old.

Any suggestions will be greatly appreciated.
Hermes YanHermes Yan
Logic just needs some tweaking. On insert add the value. But on update need to compare the old and new values and figure out the difference and add that to the total. Also needs to cater for delete of the record and undelete of the record.
Jim JamJim Jam
I would consider using Aggregate SOQL for this. You could do something like ..
AggregateResult[] groupedResults
  = [SELECT SUM(NumberField) totalSum FROM order_object];
Decimal totalOrders = Decimal.valueOf (groupedResults[0].get('totalSum'));

to get the toal sum and update your running sum field.

Have a look at http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_agg_fns.htm