**GlideAggregate SUM Returning Unexpected Multiple Outputs in Background Scripts**

DurgaPrasadCH
Tera Contributor

Hi everyone,

I am currently learning GlideAggregate and trying to use the SUM aggregate on the Incident table.

 

I used the below script in Background Scripts:

 

var ga = new GlideAggregate("incident");

ga.addAggregate("SUM", "reassignment_count");

ga.query();

if (ga.next()) {

var total = ga.getAggregate("SUM", "reassignment_count");

gs.info(total);

}

 

The field reassignment_count is an Integer type field. However, sometimes I am getting the output as 0.

If I use while(ga.next()) instead of if(ga.next()), then I get outputs like:

0
21
18
3

 

I am wondering whether old Background Scripts or grouped results are also getting executed along with my current script.

 

Can anyone please explain why this is happening and how to properly test GlideAggregate SUM in Background Scripts?

 

Thanks in advance.

1 ACCEPTED SOLUTION

Rafael Batistot
Kilo Patron

Hi @DurgaPrasadCH 

GlideAggregate always groups results, even if you don’t call groupBy() 

Without groupBy(), ServiceNow groups implicitly, so if (ga.next()) may return a group whose SUM is 0, while (ga.next()) shows all grouped results, which is why you see multiple numbers Nothing from old Background Scripts is being reused or re-executed

 

See the correct way to get a single total SUM:

 

var ga = new GlideAggregate('incident');
ga.addAggregate('SUM', 'reassignment_count');
ga.groupBy('sys_class_name');
ga.query();

if (ga.next())
gs.info(ga.getAggregate('SUM', 'reassignment_count'));

If this response was helpful, please mark it as Helpful and, if applicable, as Correct, this helps other users find accurate and useful information more easily.

View solution in original post

1 REPLY 1

Rafael Batistot
Kilo Patron

Hi @DurgaPrasadCH 

GlideAggregate always groups results, even if you don’t call groupBy() 

Without groupBy(), ServiceNow groups implicitly, so if (ga.next()) may return a group whose SUM is 0, while (ga.next()) shows all grouped results, which is why you see multiple numbers Nothing from old Background Scripts is being reused or re-executed

 

See the correct way to get a single total SUM:

 

var ga = new GlideAggregate('incident');
ga.addAggregate('SUM', 'reassignment_count');
ga.groupBy('sys_class_name');
ga.query();

if (ga.next())
gs.info(ga.getAggregate('SUM', 'reassignment_count'));

If this response was helpful, please mark it as Helpful and, if applicable, as Correct, this helps other users find accurate and useful information more easily.