0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Apexの集計レコードとMapの基本使いポイント

Last updated at Posted at 2022-10-11

要件

Apexの基本ポイント
①Countなどの集合変数
  List<AggregateResult>
AggregateResult.get('fieldName expr0,1,2')
②Mapの使用方法
 Map<id,Account> accounts = new Map<id,Account>( [Select Id, Name from Account Where Id IN :recordIds])
map.keysets().map.values(), map.get(key)

public class AccountProcessor{
  @future
  public static void countContacts(List<Id> recordIds) {
    Map<id,Account> accounts = new Map<id,Account>( [Select Id, Name from Account Where Id IN :recordIds]);
    
    List<AggregateResult> arr = [select accountid,count(id) 
                             from contact Where accountid  IN :recordIds group by accountid ];
                             
    For (AggregateResult ar : arr){
        System.debug( ar.get('AccountId') + '---' + ar.get('expr0'));
        String accId = ar.get('AccountId').toString();
        accounts.get(accId).Number_Of_Contacts__c =  (Decimal)ar.get('expr0');
    }
    
    update(accounts.values());
  }
}

Countだけをとるとき

List<AggregateResult> arr = [Select count(id) CNT from account];
System.debug(arr.get(0).get('CNT'));

Or

AggregateResult arr0 = [Select count(id) CNT from account];
System.debug('Count:' + arr0.get('CNT'));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?