I have a requirement to rollup the Average, Max, Min, total values on many Child records (over 50,000) to fields on the parent object. I am running into an issue where my Aggregate results query is hitting the too many Query rows error. Does anyone have a solution for how to code this in a way where I can avoid the limit.
Here is the query that is hitting the error, The rest of the code just takes those values and applies them to the parent field assuming the value has changed.
private AggregateResult[] aggregatePaymentAmounts(Set<Id> GAUIds) {
return [SELECT
npsp__General_Accounting_Unit__c GAU
,SUM(npsp__Amount__c) Total, MIN(npsp__Amount__c) Min, MAX(npsp__Amount__c) Max, Avg(npsp__Amount__c) average, COUNT(id) Num
FROM
npsp__Allocation__c
WHERE
npsp__Payment__c != null
AND
(npsp__Payment__r.npe01__Opportunity__r.Type != 'Transfer' AND npsp__Payment__r.npe01__Opportunity__r.Type != 'Third Party Payor')
AND
(npsp__Payment__r.npe01__Opportunity__r.StageName = 'Revocable Planned Gift' OR npsp__Payment__r.npe01__Opportunity__r.StageName = 'Pledged' OR npsp__Payment__r.npe01__Opportunity__r.StageName = 'Received' OR npsp__Payment__r.npe01__Opportunity__r.StageName = 'Awarded')
AND
(npsp__Payment__r.npe01__Opportunity__r.RecordType.Name = 'Gift' OR npsp__Payment__r.npe01__Opportunity__r.RecordType.Name = 'Grant' OR npsp__Payment__r.npe01__Opportunity__r.RecordType.Name = 'Matching Gift')
AND
npsp__General_Accounting_Unit__c IN :GAUIds
GROUP BY
npsp__General_Accounting_Unit__c];
}