0

I need to get Account names and asset count for each account. From Asset table I can get AccountId and asset count. But I need to get Account names also. This is where I stuck. How to use Ids, from aggregate query and get Account names by Id.

1

If you want non-aggregated fields from records identified through an aggregate query, you need to make a second, non-aggregate, SOQL query.

For example.

List<AggregateResult> aggregateResults = [
    SELECT AccountId, SUM(Amount) amt
    FROM Opportunity
    GROUP BY AccountId
];
Set<Id> accountIds = new Set<Id>();

for (AggregateResult ar : aggregateResults) {
    accountIds.add(ar.get('AccountId'));
}

then, to get the names of the grouped objects,

Map<Id, Account> accountMap = new Map<Id, Account(
    [SELECT Name
     FROM Account
     WHERE Id IN :accountIds]
);

The Map then makes it easy to connect from the aggregate data to the parent record information. Adapting these example queries to the scenario described above should be straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.