AggregateResult
クエリに MAX() などの集計関数が含まれる場合、このオブジェクトには、query() で返される結果が含まれます。AggregateResult は sObject ですが、Contact など、他の sObject オブジェクトとは異なり、参照のみでクエリ結果にのみ使用されます。
QueryResult オブジェクトには、クエリに一致する sObject レコードの配列である records 項目があります。たとえば、次のクエリは records 項目で Contact レコードの配列を返します。
1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17SELECT Id, LastName
18FROM Contact
19WHERE FirstName = 'Bob'SOQL クエリに集計関数が含まれる場合、結果は、Contact など、標準オブジェクトのレコード配列ではなく、集計データのセットになります。そのため、records 項目では、AggregateResult レコードの配列を返します。
集計関数の詳細は、『Salesforce SOQL および SOSL リファレンス』の「Aggregate Functions」を参照してください。
項目
各 AggregateResult オブジェクトには、SELECT リストのアイテムごとに別個の項目が含まれます。Enterprise WSDL の場合、各アイテムの結果を取得するには、WSC クライアントフレームワークを使用するときに AggregateResult オブジェクトに対して getField() をコールします。Partner WSDL の場合、各アイテムの結果を取得するには、sObject オブジェクトに対して getField() をコールします。
Enterprise WSDL で動作する例については、「サンプルコード —Java」および「サンプルコード —C#」を参照してください。
サンプルコード —Java
1swfobject.registerObject("clippy.codeblock-1", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public void queryAggregateResult() {
18 try {
19 String groupByQuery = "SELECT Account.Name n, " +
20 "MAX(Amount) max, MIN(Amount) min " +
21 "FROM Opportunity GROUP BY Account.Name";
22 QueryResult qr = connection.query(groupByQuery);
23 if (qr.getSize() > 0) {
24 System.out.println("Query returned " +
25 qr.getRecords().length + " results."
26 );
27 for (SObject sObj : qr.getRecords()) {
28 AggregateResult result = (AggregateResult) sObj;
29 System.out.println("aggResult.Account.Name: " +
30 result.getField("n")
31 );
32 System.out.println("aggResult.max: " +
33 result.getField("max")
34 );
35 System.out.println("aggResult.min: " +
36 result.getField("min")
37 );
38 System.out.println();
39 }
40 } else {
41 System.out.println("No results found.");
42 }
43 System.out.println("\nQuery successfully executed.");
44 } catch (ConnectionException ce) {
45 ce.printStackTrace();
46 }
47}
48サンプルコード —C#
1swfobject.registerObject("clippy.codeblock-2", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17private void testAggregateResult()
18{
19 try
20 {
21 QueryResult qr = null;
22
23 binding.QueryOptionsValue = new QueryOptions();
24
25 String soqlStr = "SELECT Name, " +
26 "MAX(Amount), " +
27 "MIN(Amount) " +
28 "FROM Opportunity " +
29 "GROUP BY Name";
30
31 qr = binding.query(soqlStr);
32
33 if (qr.size > 0)
34 {
35
36 for (int i = 0; i < qr.records.Length; i++)
37 {
38
39 sforce.AggregateResult ar = (AggregateResult)qr.records[i];
40
41 foreach (XmlElement e in ar.Any)
42 Console.WriteLine(
43 "{0} - {1}",
44 e.LocalName,
45 e.InnerText
46 );
47
48 }
49 }
50 else
51 {
52 Console.WriteLine("No records found");
53 }
54 Console.WriteLine("Query successfully executed.");
55 }
56 catch (Exception ex)
57 {
58 Console.WriteLine(
59 "\nFailed to execute query successfully." +
60 "error message was: \n" +
61 ex.Message
62 );
63
64 }
65}
66