glideAggregate Sum not populating field

ssturde
Kilo Expert

I have parent records with child records. The child records each record unique values of impacted users. When I attempt to use glideAggregate to sum the individual child values into a single field in the parent record, I get no value returned.

Any help is appreciated:

var rec = new GlideAggregate('u_so_incident_impacts');  
rec.groupBy('number');  
rec.addAggregate('SUM','u_users_in_game_impacted');  
rec.query();  
while(rec.next()){  
  var count = rec.getAggregate('SUM','u_users_in_game_impacted');  
  var usam = count.addAggregate('SUM','u_total_users_impacted');  
    current.u_total_users_impacted = usam;
  // find and store the count value in the related record.  
}  

I found the original script on another thread found here:

Add values from field on a related list

1 ACCEPTED SOLUTION

OK, here's the script I used in the calculated field on the dictionary entry for incident.u_total_users_impacted...



(function calculatedFieldValue(current) {



  var childTable = 'u_so_incident_impacts';


  var numberField = 'u_users_in_game_impacted'; // what do we want to sum up?



  var count = 0;


  var gr = new GlideRecord(childTable);


  gr.addQuery('u_parent', current.sys_id);


  gr.query();



  while (gr.next()) {


  var n = parseInt(gr.getValue(numberField), 10);


  count += n;


  }


  return count;   // return the calculated value



})(current);



Something to keep in mind... the calculated field isn't STORED in the database until you update the record. So you MAY incur performance issues if you present a list and it has to do all these gliderecord lookups to show you the list (assuming you put that field in the list layout.)



To improve performance, do a one-time forced-update to the incident records so it retally's the numbers and stores them. Going forward, they'll maintain themselves.



var inc = new GlideRecord('incident');


inc.query();


while (inc.next()) {


  inc.setWorkflow(false);


  inc.autoSysFields(false);


  inc.setForceUpdate(true);


  inc.update();


}



You can run this from scripts background or create a Fix script if you like (makes it easier to move from dev to prod in an update set.)



Fix Scripts - ServiceNow Wiki


View solution in original post

30 REPLIES 30

Fantastic! Amazing! Awesome! Thank you so much! This worked perfectly. Sorry for the wild goose chase on glideAggregate. I appreciate you sticking with me through it all.