Need some help with a GlideAggregate sum script

mitzaka
Mega Guru

Hi SNC,

Case goes like this - I have a field on the problem form (u_total), that I want to be populated with the sum of the values from the field 'u_impacted_allocation' in each related to the problem incident. Below is my script which does not sum them up currently. What am I missing?

(function executeRule(current, previous /*null when async*/) {

  var gr1 = new GlideAggregate('incident');

  gr1.addQuery('problem_id', current.sys_id); //finds the outages for the incidents related to the current problem

  gr1.addAggregate('SUM','u_impacted_allocation');

  gr1.query();

  while(gr1.next()){

  var total = gr1.getAggregate('SUM','u_impacted_allocation'); //calculates the total proportional impact allocation

  current.u_total = total; //sets the calculation to the field on the problem form

  current.update();

  }

})(current, previous);

10 REPLIES 10

karthiknagaramu
Kilo Sage

Try below,


var gr1 = new GlideAggregate('incident');


  gr1.addQuery('problem_id', current.sys_id); //finds the outages for the incidents related to the current problem


  gr1.addAggregate('COUNT');


  gr1.query();


if (gr1..next()) {


    current.u_total= gr1.getAggregate('COUNT');


current.update();


}


Bharath40
Giga Guru

Hi,



var gr1 = new GlideAggregate('incident');


  gr1.addQuery('problem_id', current.sys_id); //finds the outages for the incidents related to the current problem


  gr1.addAggregate('COUNT','u_impacted_allocation');         /by u_impacted_allocation'


  gr1.query();


if (gr1..next()) {


    current.u_total= gr1.getAggregate('COUNT',u_impacted_allocation');


current.update();


}        


snowcone
Mega Guru

Dimitar,


You should add gr1.groupBy('problem_id'); before you filter on problem so that you get a collection of records whose aggregate you can then calculate. What you are doing is querying individual records - in which case you have to iterate them (unnecessarily) to sum up individually. Here is a similar example that will work without iterating:




var gr = new GlideAggregate("alm_asset");
gr.groupBy("assigned_to");
gr.addQuery("assigned_to",   current.caller_id);
gr.addAggregate('SUM', 'cost');
gr.query();



if (gr.next()) {
gs.addInfoMessage(" COST " +   gr.getAggregate('SUM','cost')   );
}

Grouping actually made sense. I used it in my solution - I will paste it shortly below. Thanks!