从表中检索最新记录(Oracle SQLPlus)

时间:2013-07-15 11:42:37

标签: sql database oracle oracle11g greatest-n-per-group

我有这张桌子:
线程(ThreadID,ThreadType,PostDate,PostTime,Topic,Detail,UserID)
主键= ThreadID,外键=用户ID
我想从每个用户那里检索最新的帖子以及他们的帖子详细信息,我尝试了以下语句

 --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  

但似乎结果返回不同,第一个应该是正确的,因为它返回每个用户的最新帖子(结果中没有重复的UserID),但第二个返回每个用户的每个帖子(重复的UserID) )。
我想知道为什么,因为我想要检索每个用户的最新帖子及其帖子详细信息

2 个答案:

答案 0 :(得分:3)

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;

答案 1 :(得分:0)

试试这个:

    SELECT T1.UserID, T1.ThreadID, T1.PostTime AS LastPost  
    FROM Thread T1
    WHERE T1.PostTime = 
    (
    SELECT MAX(T2.PostTime)
    FROM Thread T2
    WHERE T2.UserID = T1.UserID
          AND T2.ThreadID = T1.ThreadID
    )