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

Tony DiRienzo
Giga Guru

Since you want it to only print out one result, you should move the gs.addInfoMessage(total) outside of the while loop.   This should do what you want:



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);


VaranAwesomenow
Mega Sage

Dear Edwin,



Just made an after business rule on time_card to achieve what you are look for as an info message on the time card when someone submits it. This should work from project table as well once you update the query variable.



script :



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


var query = 'category=task_work'; // need to update this to have the correct query, I believe it is 'u_project=' + current.sys_id


      var total = 0; // as mentioned by @Michael Ritchie


var grTc = new GlideRecord('time_card');


grTc.addEncodedQuery(query);


grTc.query();


while(grTc.next()) {


total+= grTc.sunday + grTc.monday + grTc.tuesday +


grTc.wednesday + grTc.thursday + grTc.friday +


grTc.saturday;


}


gs.addInfoMessage("Total Hrs so far = " + total);




})(current, previous);


find_real_file.png



find_real_file.png



Output :



find_real_file.png