+ Start a Discussion
Patrick FordPatrick Ford 

How to pull RecordType.Name from an aggregated result?

I've got the following code
 
User u =   [SELECT Id 
            FROM User
            Where Email='admin@***.org'];

for(AggregateResult objAgr : [SELECT   RecordType.Name, SUM(DurationHours__c)
                              FROM     Event 
                              WHERE    OwnerId = :u.Id
                              GROUP BY RecordType.Name])
{
    String label = string.valueof(objAgr.get('RecordType.Name'));
    Double total = double.valueof(objAgr.get('expr0'));
    system.debug(label + ' | ' + total);
}

I get an error when running this from an execute anonymous window that says:

System.SObjectException: Invalid field RecordType.Name for AggregateResult

I am able to use this exact same code for a similar query, except instead of grouping by RecordType.Name, I group by ActivityDate. This works perfectly. So how do I get RecordType.Name results?
Best Answer chosen by Patrick Ford
Alain CabonAlain Cabon
It is strange indeed.

The workaround is to use an alias for the field (here RecordTypeName).
 
User u =   [SELECT Id 
            FROM User
            Where Email='admin@***.org'];

for(AggregateResult objAgr : [SELECT   RecordType.Name RecordTypeName, SUM(DurationHours__c)
                              FROM     Event 
                              WHERE    OwnerId = :u.Id
                              GROUP BY RecordType.Name])
{
    String label = string.valueof(objAgr.get('RecordTypeName'));
    Double total = double.valueof(objAgr.get('expr0'));
    system.debug(label + ' | ' + total);
}