Sum up field values(decimal) of same field in different record in same table?

Edwin Fuller
Tera Guru

I have the below script the is giving me the total time charge to a particular task per record. Can someone help me in getting the script to add all of the different totals into one combined total?For example the below screen shot, shows 127.0 and 20.0. I would like the script to print out 147 which is the total combined.

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

var gr = new GlideRecord('time_card');

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

gr.query();

while (gr.next()) {

var total = gr.sunday + gr.monday + gr.tuesday + gr.wednesday + gr.thursday + gr.friday + gr.saturday;

gs.addInfoMessage(total);

//gr.setWorkflow(false);

//gr.update();

}

})(current, previous);

find_real_file.png

1 ACCEPTED SOLUTION

Michael Ritchie
ServiceNow Employee
ServiceNow Employee

You need to move total outside the loop:


var total = 0;


var gr = new GlideRecord('time_card');


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


gr.query();


while (gr.next()) {


      total = total + gr.sunday + gr.monday + gr.tuesday + gr.wednesday + gr.thursday + gr.friday + gr.saturday;


      gs.addInfoMessage(total);


      //gr.setWorkflow(false);


      //gr.update();


}


View solution in original post

6 REPLIES 6

Michael Ritchie
ServiceNow Employee
ServiceNow Employee

You need to move total outside the loop:


var total = 0;


var gr = new GlideRecord('time_card');


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


gr.query();


while (gr.next()) {


      total = total + gr.sunday + gr.monday + gr.tuesday + gr.wednesday + gr.thursday + gr.friday + gr.saturday;


      gs.addInfoMessage(total);


      //gr.setWorkflow(false);


      //gr.update();


}


I think just small correction, you would have mistakenly typed it,



total = total + gr.sunday + gr.monday + gr.tuesday + gr.wednesday + gr.thursday + gr.friday + gr.saturday;


Thanks, edited post with correction.


Shishir Srivast
Mega Sage

Hello Edwin,



May be you can try to get the total saved in one custom field and then use the GlideAggregate SUM to calculate the sum of that custom field for all the record.


GlideAggregate - Global