您的位置:首页 > 编程语言

利用SOQL 的Aggregate Functions (SUM,MAX,MIN...) 让代码更加的优雅,高效和稳定

2017-10-13 00:00 344 查看
1.没用Aggregate Functions的代码如下:

Set<Id> set_AccountIds = new Set<Id>();
map<Id,list<Datetime>> map_AccountId_LastModifiedDate = new map<Id,list<Datetime>>();
for(ObjectTerritory2Association OTTAobj: [SELECT ObjectId, LastModifiedDate FROM ObjectTerritory2Association]){
if(map_AccountId_LastModifiedDate.get(OTTAobj.ObjectId) == null) {
map_AccountId_LastModifiedDate.put(OTTAobj.ObjectId, new list<Datetime>());
}
map_AccountId_LastModifiedDate.get(OTTAobj.ObjectId).add(OTTAobj.LastModifiedDate);
}
for(Account account : [SELECT Id, Last_Batch_Job_Run_DateTime__c FROM Account WHERE Id IN :map_AccountId_LastModifiedDate.keyset()]){
map_AccountId_LastModifiedDate.get(account.Id).sort();
Datetime maxLastModifiedDate = map_AccountId_LastModifiedDate.get(account.Id).get(map_AccountId_LastModifiedDate.get(account.Id).size() -1);
if(account.Last_Batch_Job_Run_DateTime__c == null){
set_AccountIds.add(account.Id);
}else if(account.Last_Batch_Job_Run_DateTime__c < maxLastModifiedDate){
set_AccountIds.add(account.Id);
}
}


2.使用Aggregate Functions的代码如下:

Set<Id> accountIds = new Set<Id>();
Map<Id,Datetime> accountDateMap = new map<Id,Datetime>();
AggregateResult[] groupedResults = [SELECT ObjectId, Max(LastModifiedDate) FROM ObjectTerritory2Association GROUP BY ObjectId];
for (AggregateResult ar : groupedResults)  {
accountDateMap.put(String.valueOf(ar.get('ObjectId')), (Datetime)ar.get('expr0'));
}
for(Account account : [SELECT Id, Last_Batch_Job_Run_DateTime__c FROM Account WHERE Id IN :accountDateMap.keyset()]){
if(account.Last_Batch_Job_Run_DateTime__c == null){
accountIds.add(account.Id);
}else if(account.Last_Batch_Job_Run_DateTime__c < accountDateMap.get(account.Id)){
accountIds.add(account.Id);
}
}


利用Aggregate Functions 重写的代码2,更加易于阅读和高效

想象一下 :例如ObjectTerritory2Association 里面有1W条数据,ObjectId 分类只有3千
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Apex Aggregate
相关文章推荐