GlideAggregate Question

Rishabh Khare
Giga Contributor

Hi Everyone,

I am new to this can anyone please tell me why we use if block while counting record using GlideAggregate.

 

var count = new GlideAggregate('u_test');
count.addAggregate('COUNT');
count.query();
var computer=0;
if(count.next())
    {
        computer=count.getAggregate('COUNT');
        gs.info(computer);
        
    }
    What this line if(count.next()) says When I removed this if block then also answer is same.

var count = new GlideAggregate('u_test');
count.addAggregate('COUNT');
count.query();
var computer=0;
count.next();

   computer=count.getAggregate('COUNT');
   gs.info(computer);
        
    
        

7 REPLIES 7

AnubhavRitolia
Mega Sage
Mega Sage

I guess for GlideAggregate, If block is not required. 

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

Thanks
Anubhav Ritolia
ServiceNow Rising Star 2023

Then why we are using count.next() here when we dont have to iterate to each object.

AnubhavRitolia
Mega Sage
Mega Sage

If block is used after addAggregate() function if you want to use multiple Math Functions but if you want just single Math function like Count, it is not required.

Please find example of GlideAggregate using if block:

var incidentGA = new GlideAggregate('incident');

incidentGA.addQuery('category', 'software');

incidentGA.setGroup(false);

incidentGA.addAggregate('COUNT', 'sys_mod_count');
incidentGA.addAggregate('SUM', 'sys_mod_count');
incidentGA.addAggregate('AVG', 'sys_mod_count');
incidentGA.addAggregate('MIN', 'sys_mod_count');
incidentGA.addAggregate('MAX', 'sys_mod_count');
incidentGA.addAggregate('STDDEV', 'sys_mod_count');

incidentGA.query();

if (incidentGA.next()) {
  gs.info('COUNT: ' + incidentGA.getAggregate('COUNT', 'sys_mod_count'));
  gs.info('SUM: ' + incidentGA.getAggregate('SUM', 'sys_mod_count'));
  gs.info('AVG: ' + incidentGA.getAggregate('AVG', 'sys_mod_count'));
  gs.info('MIN: ' + incidentGA.getAggregate('MIN', 'sys_mod_count'));
  gs.info('MAX: ' + incidentGA.getAggregate('MAX', 'sys_mod_count'));
  gs.info('STDDEV: ' + incidentGA.getAggregate('STDDEV', 'sys_mod_count'));
}

 

Please mark this correct and helpful.

Please mark this as correct answer and helpful if it resolved, or mark this helpful if this help you to reach towards solution.

Thanks
Anubhav Ritolia
ServiceNow Rising Star 2023

Yousaf
Giga Sage

Hi Rishabh,

You do not need to use if block in the code you share. 
If is generally used for condition and specifically you can use if with GlideAggregate when there is no groupby,orderby,distinct, since it will return one record. (not must but you can use)
If you will use groupby,orderby,distinct, then you have to use while because it will return multiple records.

 

Mark Correct or Helpful if it helps.


***Mark Correct or Helpful if it helps.***