function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TROGTROG 

Apex Aggregation when key is non-groupable?

I am trying to create a trigger that sums up field 'x' on a custom object (CO) into a total field, 'y', for all CO's with the same attribute 'z'.  Note, because this is suming data on the same object, I can't use rollups, OOB nor Rollup Helper.  I tried using SOQL's aggregate function, but the key that I like to group-by for the sum, 'z', is considered non-groupable.  (It is a lookup to a custom object...I don't get why it's non-groupable).  What other options do I have for aggregating this data within an APEX trigger?  All I can think of is via a loop and y = y + z type of thing, but that seems highly inefficient for something that should be quite basic.  Seems like there should be something like a list or map method that can add up values.

Thanks!  Tim
pconpcon
Can you please include the AggregateResult query you are using?  You should be able to group by a lookup to a custom object (I've done it before).  If for some reason it's not groupable, you can always just query all the objects that meet the same criteria as your aggregate query and do the sumation yourself.  It will most likely be inefficient and may cause you to hit the CPU/row limit governor, but if it's not a large number of objects, you may not.