Newer Version Available
AggregateResult
Results are returned in AggregateResult only if a query() or queryMore() call includes the aggregate function. If the call doesn't contain an aggregate function, the results are returned in the QueryResult SObject.
For example, this query returns an array of Contact records in the records field.
1SELECT Id, LastName
2FROM Contact
3WHERE FirstName = 'Bob'When a SOQL query contains an aggregate function, the record field returns an array of AggregateResult records. .
Fields
Each AggregateResult object contains a separate field for each item in the SELECT list. For the Enterprise WSDL, retrieve the result for each item by calling getField() on an AggregateResult object when using WSC client framework. For the Partner WSDL, retrieve the result for each item by calling getField() on an object.
Sample Code—Java
1public void queryAggregateResult() {
2 try {
3 String groupByQuery = "SELECT Account.Name n, " +
4 "MAX(Amount) max, MIN(Amount) min " +
5 "FROM Opportunity GROUP BY Account.Name";
6 QueryResult qr = connection.query(groupByQuery);
7 if (qr.getSize() > 0) {
8 System.out.println("Query returned " +
9 qr.getRecords().length + " results."
10 );
11 for (SObject sObj : qr.getRecords()) {
12 AggregateResult result = (AggregateResult) sObj;
13 System.out.println("aggResult.Account.Name: " +
14 result.getField("n")
15 );
16 System.out.println("aggResult.max: " +
17 result.getField("max")
18 );
19 System.out.println("aggResult.min: " +
20 result.getField("min")
21 );
22 System.out.println();
23 }
24 } else {
25 System.out.println("No results found.");
26 }
27 System.out.println("\nQuery successfully executed.");
28 } catch (ConnectionException ce) {
29 ce.printStackTrace();
30 }
31}Sample Code—C#
1private void testAggregateResult()
2{
3 try
4 {
5 QueryResult qr = null;
6
7 binding.QueryOptionsValue = new QueryOptions();
8
9 String soqlStr = "SELECT Name, " +
10 "MAX(Amount), " +
11 "MIN(Amount) " +
12 "FROM Opportunity " +
13 "GROUP BY Name";
14
15 qr = binding.query(soqlStr);
16
17 if (qr.size > 0)
18 {
19
20 for (int i = 0; i < qr.records.Length; i++)
21 {
22
23 sforce.AggregateResult ar = (AggregateResult)qr.records[i];
24
25 foreach (XmlElement e in ar.Any)
26 Console.WriteLine(
27 "{0} - {1}",
28 e.LocalName,
29 e.InnerText
30 );
31
32 }
33 }
34 else
35 {
36 Console.WriteLine("No records found");
37 }
38 Console.WriteLine("Query successfully executed.");
39 }
40 catch (Exception ex)
41 {
42 Console.WriteLine(
43 "\nFailed to execute query successfully." +
44 "error message was: \n" +
45 ex.Message
46 );
47
48 }
49}