Salesforce Cross Object SOQL Query - salesforce

I have a custom object called 'Billings'. On that object there is a custom lookup field to the Opportunity. I'm trying to query all the 'Billings' records associated with a particular Opportunity. I get "Unknown error parsing query".
SELECT Id, StageName,
( SELECT Name, Email FROM Billings__C )
FROM Opportunity WHERE Opportunity ID = '0011000002mfTil'

For Nested Queries in SOQL, you need to use the '__r' suffix on the Child Relationship Name for the field that provides the look-up from the Child Record to the Parent.
In your case, this is most likely 'Billings__r'. However, to confirm, go to the Billings object and click on the custom field that provides the lookup to the Opportunity object. In the "Lookup Options" section on the Custom Field details screen you will see the official Child Relationship Name without the '__r' suffix. This is the correct name for this relationship for a Nested Query.
The other error in your query is that you have "WHERE Opportunity Id =". It should just be "WHERE Id ="
Based on the information you provided, your query should be:
SELECT Id, StageName, ( SELECT Name, Email FROM Billings__r ) FROM Opportunity WHERE ID = '0011000002mfTil'

Related

SOQL - Count of records where the parent hasn't had child records in 1 year

I am trying to create a SOQL query (and later a report) in Salesforce that generates the following data:
Count of Child records grouped by Parent records where the Parent does not have child records created in the past year.
I tried this first; however, salesforce returned an error stating 'Nesting of semi join sub-selects is not supported'.
SELECT Id, Name, Training_Course__c
FROM Training_Record__c
WHERE Training_Course__c IN (
SELECT Id
FROM Training_Course__c
WHERE Id NOT IN (
SELECT Training_Course__c
FROM Training_Record__c
WHERE CreatedDate != Last_n_Days:365
)
)
The requirements are to use a single query to obtain the data requested without forcing them to run two reports and use Excel to get the data. I'm not sure if that's possible given Salesforce's constraints.
Is this possible in SOQL? If so, what can I do differently?
This is not perfect but a decent start, you'd need to manually call count/size/length on the child records (exact method depends on your client application's language). In a SF report you can group by parent Id and call it a day. Read about "cross filters" in SF reports.
SELECT Id, Name,
(SELECT Id FROM Opportunities)
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity WHERE CloseDate = LAST_N_DAYS:365)
LIMIT 100
This will not compile:
SELECT AccountId, COUNT(Id)
FROM Opportunity
WHERE AccountId NOT IN (SELECT AccountId FROM Opportunity WHERE CloseDate = LAST_N_DAYS:365)
Error: The inner and outer selects should not be on the same object type
but if you really need something like that you could experiment, do it in 2 steps. Create helper field on account, tick the checkbox for eligible accs (with some nightly batch job maybe), then query based on that.
(normally you could do it with rollup summary field from opps to account but rollups have to be based on solid data, "deterministic". "LAST 365 DAYS", "TODAY" etc can't be used as rollup criteria)

Soql object has multiple lookups to user

Afternoon,
I am gathering data from the LiveChatTranscript and there are multiple references to user as lookup fields. How do I pick which property I want to use as my reference to user?
LiveChatTranscript properties
LastModifiedById Lookup(User)
CreatedById Lookup(User)
OwnerId Lookup(User,Group)
query
-webroot-/query/?q=select chatkey, caseid, status,requesttime, starttime, endtime,endedby,name,ReferrerUri,platform,location, waittime,body,supervisortranscriptbody, case.description, ownerid,ownerid.user.alias?? from livechattranscript where chatkey = '12345'
In this case, owner is the field name. It looks up to the user object. No need to include the object name there. Just drop the id potion for ownerid.
Use owner.alias.

How To Query Opportunity History Object in Salesforce

We have opportunity History report type in salesforce Reports & Dashboard where we can use fields like "From Stage" & "To Stage". How can we use those two fields in SOQL? I tried but there is no such field on "Opportunity History" object. Is there any workaround for the same? (Need to use this in SOQL only no custom coding)
If you are looking for the From and To values, you need to query OpportunityFieldHistory.
SELECT CreatedDate, OldValue, NewValue
FROM OpportunityFieldHistory
WHERE opportunityid = 'yourid' AND Field = 'StageName'
ORDER BY createddate

Salesforce - Querying to fetch data from junction object and Accounts

I have a junction object called "JIRA_Data" and its linked/ related to Accounts. How do I query to fetch data from this relationship. I am trying to extract id,type from Account object and Name from JIRA_Data junction object.
Could anyone assist. Thanks
You could do it multiple ways depending on how you want the data. If you query it from the parent account it would be something to the effect:
SELECT Id, Name, (Select ID, Name, Other_Parent__r.Name FROM Jira_Datas__r) FROM Account
or from the junction
SELECT Id, Name, Account.Name, Other_Parent__r.Name FROM Jira_Data__c

Salesforce - Apex - query accounts based on Activity History

Hey Salesforce experts,
I have a question on query account information efficiently. I would like to query accounts based on the updates in an activityHistory object. The problem I'm getting is that all the accounts are being retrieved no matter if there's "complete" activeHistory or not. So, Is there a way I can write this query to retrieve only accounts with activeHistory that has status="complete" and Type_for_reporting='QRC'?
List<Account> AccountsWithActivityHistories = [
SELECT
Id
,Name
,( SELECT
ActivityDate
,ActivityType
,Type_for_Reporting__c
,Description
,CreatedBy.Name
,Status
,WhatId
FROM ActivityHistories
WHERE Status ='complete' and Type_for_Reporting__c = 'QRC'
)
FROM Account
];
You have a WHERE clause on the histories but you still miss one on the Account level.
For example this would return only Accounts that have Contacts:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact) // try with NOT IN too
With Activities it's trickier because they don't like to be used in WHERE in that way.
http://www.salesforce.com/us/developer/docs/officetoolkit/Content/sforce_api_calls_soql_select.htm
The following objects are not currently supported in subqueries:
ActivityHistory
Attachments
Event
EventAttendee
Note
OpenActivity
Tags (AccountTag, ContactTag, and all other tag objects)
Task
Additionally the fine print at the bottom of ActivityHistory definition is also a bit discouraging.
The following restrictions on users who don’t have “View All Data” permission help prevent performance issues:
In the main clause of the relationship query, you can reference only
one record. For example, you can’t filter on all records where the
account name starts with ‘A’; instead, you must reference a single
account record.
You can’t use WHERE clauses.
You must specify a limit of 499 or fewer on the number of rows returned in the list.
You must sort on ActivityDate in ascending order and LastModifiedDate in descending order; you can display nulls last. For
example: ORDER BY ActivityDate ASC NULLS LAST, LastModifiedDate DESC.
Looks like you will need multiple queries. Go for Task (or Event, depending for which the custom field is visible), compose a set of AccountIds and then query the Accounts?
Or you can manually filter through list from your original query, copying accounts to helper list:
List<Account> finalResults = new List<Account>();
for(Account a : [SELECT...]){
if(!a.ActivityHistories.isEmpty()){
finalResults.add(a);
}
}

Resources