Search code examples
sqldatabaseoracleoracle11ggreatest-n-per-group

Retrieving the latest record from a Table (Oracle SQLPlus)


I've got this table:
Thread(ThreadID, ThreadType, PostDate, PostTime, Topic, Detail, UserID)
Primary key = ThreadID, Foreign Key = UserID
I want to retrieved the latest Post together with their post detail from Every User, and I have try the following statements

 --Without Posting details  
SELECT UserID, MAX(PostTime) AS lastPost  
FROM Thread  
GROUP BY UserID  
ORDER BY UserID  

--With Posting details  
SELECT UserID, ThreadID, MAX(PostTime) AS lastPost  
FROM Thread   
GROUP BY UserID, ThreadID  
ORDER BY UserID  

But it seems that result return is different, the first one should be the correct one since it return latest post by each user (UserID in the result not repeated), but the 2nd one return every post from each user (repeated UserID).
I want to know why because I want to retrieved each user's latest post together with their post details


Solution

  • select *
    from (
      SELECT UserID, 
             ThreadId, 
             PostTime,
             ThreadType,
             Topic, 
             Detail,
             row_number() over (partition by userid order by posttime desc) as rn
      FROM Thread  
    ) t
    where rn = 1
    order by userid;