 ShowAll Questionssorted byDate Posted Russell baker 1

# Calculate child accounts and parent account survey score and show on parent account

I have a formula field on Account to calculate survey score. I want to calculate Average of all child account + Parent account survey scores and show that Avg. survey score on Parent account.

I have a trigger but it is showing only 1 child account survey score. Please help me to figure out the code.

```trigger childaccount on Account (after update)
{
Set<String> SetParentId = new set<String>();
Decimal Num;
for (Account a : trigger.new)
{
if(a.parentId != null)
{
}
}

if(SetParentId.size() > 0 )
{
List<Account> lstParentAcc = [ Select NPS_Score__c, Group_NPS__c , (Select NPS_Score__c From ChildAccounts) From Account where id in :SetParentId ];

For (Account ac : lstParentAcc)
{
List<Account> lstChildAcc = ac.ChildAccounts;

for( Account childAcc : lstChildAcc )
{
Num = childAcc.NPS_Score__c;
}
ac.Group_NPS__c = Num;
}
if(lstParentAcc.size() > 0 )
{
update lstParentAcc;
}
}
}```
How can I get avg. of all child account and parent account survey score. Shivram Saini
Hi Russell,

I did some changes in code. Hope this will work for you.
```trigger childaccount on Account (after update)
{
Set<String> SetParentId = new set<String>();
Decimal Num;
for (Account a : trigger.new)
{
if(a.parentId != null)
{
}
}

if(SetParentId.size() > 0 )
{
List<Account> lstParentAcc = [ Select NPS_Score__c, Group_NPS__c , (Select NPS_Score__c From ChildAccounts) From Account where id in :SetParentId ];

For (Account ac : lstParentAcc)
{
List<Account> lstChildAcc = ac.ChildAccounts;
Num = 0; //Initializing variable
for( Account childAcc : lstChildAcc )
{
Num += childAcc.NPS_Score__c; //Calculating total of child accounts
}
Num +=acc.NPS_Score__c; //Adding parent account's score
ac.Group_NPS__c = Num/(1+lstChildAcc.size()) ; //Calculating average
}
if(lstParentAcc.size() > 0 )
{
update lstParentAcc;
}
}
}```