Calculating sum of values from one table to another

rcard11
Tera Guru

Help needed!  I have two tables that have a parent child relationship.  I am trying to calculate a value from the records on the child table (estimated allocation in the related list image below) related to the parent, sum them up and set the value of a field on the parent record with the sum calculation.

 

rcard11_0-1705702131793.png

 

I've tried scripting this out via a business rule on the child table, but have not been able to get anything to work yet.  Here is my script below.  Any guidance or help would be appreciated!

 

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

    // Add your code here
    var prjid = current.u_project_record;
var sum = 0;

// Retrive all the brothers of my task
var prjTask = new GlideRecord( 'u_project_allocation' );
prjTask.addQuery( 'u_project_record', prjid );
prjTask.query();

// Sum the values
while( prjTask.next() ){
     sum += Number( prj.u_estimated_allocation );
}

// Update parent
var prj = new GlideRecord( 'u_projects' );
if( prj.get( prjid ) ){
    prj.u_allocated_hours = sum;
    prj.update();
    }

})(current, previous);
2 REPLIES 2

SanjivMeher
Kilo Patron
Kilo Patron

You can do something like this. GlideAggregate is much more efficient.

 

var prjid = current.u_project_record;
var prjTask = new GlideAggregate('u_project_allocation');
prjTask.addQuery( 'u_project_record', prjid );
prjTask.addAggregate('SUM', 'u_estimated_allocation');
prjTask.setGroup(false);
prjTask.query();
if (prjTask.next()){
var prj = new GlideRecord( 'u_projects' );
if( prj.get( prjid ) ){
    prj.u_allocated_hours =  prjTask.getAggregate('SUM', 'u_estimated_allocation');
    prj.update();
    }
}

 


Please mark this response as correct or helpful if it assisted you with your question.

Thank you for this!  I wasn't able to get it to work, but did have a few modifications of fields and table names.  Adding that below to see if there are any suggestions.

 

Tables:  u_projects i the parent table and u_project _allocation is an extension of it.

 

Fields: 

u_projects - Write the sum to a field labeled u_total_allocated_hours

rcard11_1-1706028757922.png

 

u_estimated allocation - this is the field that would be summed.

 

u_project_allocation - 

rcard11_0-1706028730020.png

 

 

I am tying to sum all records on the u_project_allocation table that have the same parent and then write that value to a field on the parent record.