Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I am trying to write a SOQL query that queries from Task the field LeadSource. In a report the name of the field that displays LeadSource is Contact/Lead. I have been trying different variations like

SELECT AccountId, Who.Name FROM Task
SELECT AccountId, Who.Lead FROM Task
SELECT AccountId, Lead FROM Task
SELECT AccountId, Who.LeadSource FROM Task

but so far unsuccessfully. Any hints appreciated.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

If you have it the SOQL Polymorphism and Type OF feature enabled in your org, then you could use TYPEOF in your SQOL to try to get this info. Something like below

SELECT 
  TYPEOF Who
    WHEN Contact THEN Phone
    WHEN Lead THEN LeadSource
    ELSE Name
  END
FROM Task

If it is not enabled, then I think you are forced to use a second query as related fields (who and What fields) are not accessible in a query for Task or Event. you would have to do a second query to get those. In that case, I would build a leadMap and a contactMap to hold the values you need.

map<Id,Contact> conMap = new map<Id,Contact>();
map<Id,Lead> leadMap = new map<Id,Lead>();
for(Task t : [Select Id, WhoId, Who.Type From Task Where YOUR CRITERIA]){
     if(t.Who.Type == 'Contact') {
         conMap.put(t.WhoId, null);
     } else {
         leadMap.put(t.WhoId, null);
     }
}
conMap.remove(null);
leadMap.remove(null);
conMap.putAll([Select Id, Name, Your_other_field_1__c, Your_other_field_2__c From Contact Where Id In : conMap.keyset()]);
leadMap.putAll([Select Id, Name, LeadSource, Your_other_field_1__c From Lead Where Id In : leadMap.keyset()]);

Now you have a map of contacts and leads that contains all related fields you might want access to.

For more info on SOQL Polymorphism and Type OF features see here http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_typeof.htm

share|improve this answer

Get the contact/lead ids :

SELECT AccountId, WhoId FROM Task

And with this WhoId you can now get the contacts or leads :

SELECT Id FROM Contact where Id = :WhoId
SELECT Id FROM Lead where Id = :WhoId
share|improve this answer
    
Thats a good workaround which I am trying to avoid and use a single query. –  Koba Aug 12 at 15:24
    
Ok, but I didn't see how doing with only one query ! –  SF_user Aug 12 at 15:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.