+ Start a Discussion
Kalle KalifKalle Kalif 

How to Limit by Distinct values in SOQL

Say i have a custom object with following records:


Id, Employee Name, Report text, report date


1, Sarah, sfakjl, 2011/3/3

2, John, blablabla, 2011/1/1

3, Sarah, blablablabal, 2011/2/2

4, Erik, some text here, 2010/12/4

5, John, example text, 2011/2/3

6, John, blakjfd, 2011/1/2


And i want to have a SOQL query that lists the Latest (ie order by report date) record for each employee - so i only want ONE record returned per employee (limited to ONE per employee name), like this:


Query result= 

Sarah, sfakjl, 2011/3/3

John, example text, 2011/2/3

Erik, some text here, 2010/12/4



How do i do this? 

Best Answer chosen by Admin (Salesforce Developers) 

Select distinct does not exist in SOQL as SFDC is object oriented and not SQL oriented......


You can acheive a similar result by trying the following: 


List<Custom__c> lCust = [Select ID, Employee_Name__c, Report_Text__c, Report_Date__c FROM Custom__c WHERE xxxxx Order By Report_Date__c];

List<Custom__c> lFINAL = New List<Custom>();

Set<String> sNames = New sString();

for (Custom__c c : lCust){

       if (sNames.Contains(c.Employee_Name__c) == FALSE){