How to get the sum of values of from integer fields

akshayp
Tera Expert

Hi,

 i have one table which has some questions and each question has some value stored in integer field

If we group the questions by category, then each category will have 2 questions with some value

Now what i want to do is multiply the values for 2 questions within same category and add it across all categories

Now i have written a script, but its not working as expected, please have a look at below code and tell me how can i get the desired results

 

 

var rec1 = new GlideRecord(‘asmt_assessment_instance_question’);
rec1.addEncodedQuery(‘instance=41c5ebfe1bbb5110c1cb4197dc4bcb6f’);
rec1.query();
while(rec1.next()){
var arr_cat = [];
if (arr_cat.indexOf(‘’+rec1.category)===-1){
arr_cat.push(‘’+rec1.category);
}
}


var total_sum= 0 ;

for (var i=0; i<arr_cat.length(); i++) {
var tempmult=1;
var rec2 = new GlideRecord(‘asmt_assessment_instance_question’);
rec2.addEncodedQuery(‘category=’+arr_cat[i]);
rec2.query();
while(rec2.next()){
tempmult = parseInt(rec2.value)*parseInt(tempmult);
total_sum = total_sum+tempmult;
}
}
gs.print(“The total sum”+total_sum);

1 ACCEPTED SOLUTION

Hey, i have gone through and by following script was able to get the desired output

 

var arr_cat = [];
var count = 0;
var rec1 = new GlideRecord(‘asmt_assessment_instance_question’);
rec1.addEncodedQuery(‘instance.sys_id=41c5ebfe1bbb5110c1cb4197dc4bcb6f’);
rec1.orderBy('category');
rec1.query();
while(rec1.next()){

if (arr_cat.indexOf(‘’+rec1.category)===-1){
arr_cat.push(‘’+rec1.category);
count = count+1;
}
}

gs.print('arr_cat ---- '+arr_cat);
gs.print('count '+count);

var total_sum = 0;

for (var i=0; i<count; i++) {
var tempmult=1;
var rec2 = new GlideRecord(‘asmt_assessment_instance_question’);
rec2.addEncodedQuery(‘instance.sys_id=41c5ebfe1bbb5110c1cb4197dc4bcb6f’);
rec2.addEncodedQuery(‘category=’+arr_cat[i]);
rec2.query();
while(rec2.next()){
tempmult = parseInt(rec2.value)*parseInt(tempmult);
}

gs.print('rec2.category - '+rec2.category.name+' and its tempmult - '+tempmult);


total_sum = total_sum+tempmult;

}

 


gs.print(“The total sum”+total_sum);

 

View solution in original post

9 REPLIES 9

RaghavSh
Kilo Patron

Try below:

var total_sum= 0 ;

for (var i=0; i<arr_cat.length(); i++) {
var tempmult=1;
var rec2 = new GlideRecord(‘asmt_assessment_instance_question’);
rec2.addEncodedQuery(‘category=’+arr_cat[i]);
rec2.query();
while(rec2.next()){
tempmult = parseInt(rec2.value)*parseInt(tempmult);
total_sum = parseInt(total_sum)+tempmult;
}
}
gs.print(“The total sum”+total_sum);


Raghav
MVP 2023

Thanks for replying, but it ain't working 

Like im always getting total_sum as 0

try changing below:

 

total_sum = parseInt(total_sum)+parseInt(tempmult);


Raghav
MVP 2023

No luck, its still returning 0 

any other way to achieve this