在Batch Apex中使用Aggregate SOQL统计查询语句及结果

In previous post, we had created a schedulable batch apex that implements Database.Batchable<sObject> in Salesforce, but if you want to use SOQL having aggregate functions like SUM(), MAX(), COUNT() on results grouped by “GROUP BY” clause in start execution, changing to interface Database.Batchable<AggregateResult> isn’t a workable way, because it fails with the below compile error :

Class must implement the global interface method: Iterable<AggregateResult> start(Database.BatchableContext) from Database.Batchable<AggregateResult>

The following sample code will explain this.

To fix this, using Apex classes that implement Iterator<AggregateResult> and Iterable<AggregateResult> seems the only way for now.

Here is the outline what we should do.
1. Create an Apex class implements Iterator<AggregateResult>.
2. Create an Apex class implements Iterable<AggregateResult>.
3. Implementing to Database.Batchable<AggregateResult>, and Using Iterable at start execution in Batch Apex.

Let’s get started.

Iterator Apex class

Create an Apex class named “AggregateResultIterator” with the following source code :

Iterable Apex class

Create an Apex class named “AggregateResultIterable” with the following source code :

Batch Apex

Then implement Batch Apex from Database.Batchable<AggregateResult>, and use Iterable<AggregateResult>, AggregateResultIterable instead of Database.QueryLocator at start execution, as the following source code :

Operation check

Run SampleAggregateBatch and check debug log.

It seems working fine! : )

Enjoy it!

Related Post

编写一个可被计划执行的Batch Apex To use batch Apex, you have to create an Apex class that implements interface Database.Batchable in Salesforce, like the following sample code: https://gist.github.com/919ab1cbae98a114c2a8e46197bd2f63 Execute batch Then you can use Database.executebatch method to execute it. https://gist.g...
用Node.js编写MangoDB+Salesforce的Heroku Scheduler batc... In previous post,I had shared how to 《Access Salesforce data via APIs(JSForce) from Outside Service》. In this post I will share about how to write a Heroku Scheduler batch for synchronizing MangoDB data to Salesforce with Node.js, like the below outline picture. ※I have no doubt that there hav...
Salesforce批量编辑 (Chrome扩展) – 在任何标准视图上进行批量插入, ... "Salesforce批量编辑"是今年发布的第二个Chrome扩展功能(第一个在这里),具备以下机能: ・轻松将标准列表视图转变成功能强大的批量编辑器 ・批量插入,批量拷贝,批量更新,批量删除,所有功能都具备,同时支持Classic跟Lightning! ・支持将数据导出到CSV文件中 ・支持从Excel直接拷贝粘贴复数行・复数列的数据 "Salesforce批量编辑"支持几乎所有的Salesforce列表视图、no页面跳转,no附加设定,no kidding。 注意 : 在Classic上使用时,请确保不要勾选“Session Settings”中的“Require H...
用Sublime Text 3架设Salesforce的快速开发环境... Why Sublime Text 3 ? 工作中接触SFDC已近两年,一直都是使用Eclipse+Force.com IDE的开发环境(Eclipse IDE安装参考此处)。虽说用着相当顺手,总是有些美中不足的地方。比如: 1.对APEX,VF语法支持的不好 ※要知道没有自动联想功能对程序猿而言,就如用Emeditor写Perl一样。 2.程序太重 ※偶尔会没有响应,重新打开还会莫名地把本地的代码自动提交到Salesforce上。。 3.没有很好用的黑色主题(想装逼都装不了。。) 最近试用了下Sublime Text 3,给我最大的感受就是,轻! 整个安装包10M不到。...