I want to find ID and name for all accounts whose industry is media, and when each account is being returned, I want it to return the last name of every contact whose created-by its alias by 'x.'
List accList = [Select Id, Name, (SELECT lastname from contacts where createdBy.alias='x') from account where industry='media' ];
system.debug(accList);
To fetch the ID and name for all accounts in the "Media" industry and retrieve the last name of every contact whose created by alias is 'x', you can use the following SOQL query:
SELECT Id, Name, (SELECT LastName FROM Contacts WHERE CreatedBy.Alias = 'x' ORDER BY CreatedDate DESC LIMIT 1)
FROM Account
WHERE Industry = 'Media'
This query uses a subquery to fetch the last name of the contacts associated with each account. The subquery filters the contacts based on their CreatedBy field's alias value being 'x' and retrieves only the most recently created contact using ORDER BY CreatedDate DESC LIMIT 1.
To complete the same task, use this code.
Please mark it as best answer if it helps you
Thanks
To fetch the ID and name for all accounts in the "Media" industry and retrieve the last name of every contact whose created by alias is 'x', you can use the following SOQL query:
This query uses a subquery to fetch the last name of the contacts associated with each account. The subquery filters the contacts based on their CreatedBy field's alias value being 'x' and retrieves only the most recently created contact using ORDER BY CreatedDate DESC LIMIT 1.
Hope this helps !
Thank you.