[SalesForce] Does SOQL SUM(CurrencyField__c) calculate correctly in MultiCurrency Org and how

I have a managed travel expense app with an AggregateResult SOQL that sums up Expenses per Day. All expenses can have different currencies and don't have to match the corporate nor the current users currency.

public with sharing class CtrlExt {
   ...

   Map<Date, Decimal> expensesPerDay = new Map<Date, Decimal>();

   for(AggregateResult ar : [SELECT dat_DatField__c day, SUM(cur_Amount__c) sum FROM   Expense__c GROUP BY dat_DatField__c]) {
      Date day = (Date) ar.get('day');
      Decimal daySum = (Decimal) ar.get('sum');

      expensesPerDay.put(day, daySum);
   }
   ...
}

My questions are:

  1. Does daySum take all the different currencies into account?
  2. The resulting Decimal daySum implicitly uses which Currency? Org, User?
  3. If I write the value of daySum into a Currency field would the Currency Iso Code be automaticall set correctly ? Correctly means that if I display it with on a VF page would the Currency and the value be what the user expects?

Best Answer

Source: http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_querying_currency_fields.htm

1) Sum() calculates different currencies correctly.

2) The result of Sum() uses the Corporate Currency of your org.

3) No, you have to set the CurrencyIsoCode to your Corporate Currency CurrencyIsoCode manually.

You can test that by adding a debug statement to your code and run this with different Corporate Currencies:

public with sharing class CtrlExt {
   ...

   Map<Date, Decimal> expensesPerDay = new Map<Date, Decimal>();

   for(AggregateResult ar : [SELECT dat_DatField__c day, SUM(cur_Amount__c) sum FROM   Expense__c GROUP BY dat_DatField__c]) {
      Date day = (Date) ar.get('day');
      Decimal daySum = (Decimal) ar.get('sum');

      System.debug('Day: ' + day + ' / Sum: ' + sum);

      expensesPerDay.put(day, daySum);
   }
   ...
}

I tested it with Euro and with US Dollar as Corporate Currency, in my case the log gives me the following values:

Corporate Currency USD: DEBUG|Day: 2014-06-09 00:00:00 / Sum: 755.74
Corporate Currency EUR: DEBUG|Day: 2014-06-09 00:00:00 / Sum: 546.25

Related Topic