'SOQL - Get the latest records based on the status from group of records

Id  Name    Status      Version CreatedDate ParentId
1   Doc1    Draft       0.1     1/23/2022   1
2   Doc 1   InReviewed  0.2     1/24/2022   1
3   Doc 1   Reviewed    0.3     1/25/2022   1
4   Doc 1   In Approved 0.4     1/27/2022   1
5   Doc 1   Approved    1.0     1/28/2022   1
6   Doc 1   Draft       1.1     1/30/2022   1
7   Doc 2   Draft       0.1     2/1/2022    7
8   Doc 2   In Reviewed 0.2     2/3/2022    7

I am looking for a SOQL query so that my result should be the latest record of document by status Such as

6   Doc 1   Draft        1.1     1/30/2022  1
8   Doc 2   In Reviewed  0.2     2/3/2022   7

This custom object will be having other columns that should be also brought with the result

Parent id is the first document id which is carry forwarded to child documents



Solution 1:[1]

If this is ContentDocument and ContentVersion - there's perfectly fine link to latest in there already. SELECT LatestPublishedVersion.Id, LatestPublishedVersion.PathOnClient FROM ContentDocument, job done.

If this is custom object - you might be best using a subquery from parent. Something similar to

SELECT Id, Name,
    (SELECT Id, Email FROM Contacts ORDER BY CreatedDate DESC LIMIT 1)
FROM Account

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eyescream