Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从表中检索最新记录(Oracle SQLPlus)_Sql_Database_Oracle_Oracle11g_Greatest N Per Group - Fatal编程技术网

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

从表中检索最新记录(Oracle SQLPlus),sql,database,oracle,oracle11g,greatest-n-per-group,Sql,Database,Oracle,Oracle11g,Greatest N Per Group,我有这张桌子: 线程(线程ID、线程类型、发布日期、发布时间、主题、详细信息、用户ID) 主键=线程ID,外键=用户ID 我想从每个用户那里检索最新的帖子及其帖子详细信息,我尝试了以下语句 --Without Posting details SELECT UserID, MAX(PostTime) AS lastPost FROM Thread GROUP BY UserID ORDER BY UserID --With Posting details SELECT

我有这张桌子:
线程(线程ID、线程类型、发布日期、发布时间、主题、详细信息、用户ID)
主键=线程ID,外键=用户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)。
我想知道原因,因为我想检索每个用户的最新帖子及其帖子详细信息

尝试以下方法:

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;
    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
    )
试试这个:

    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
    )

因为在第二个示例中,您可以
按UserID、ThreadID进行分组。在这种情况下,查询意味着“选择每个线程中每个用户的最后一篇文章”,因为线程是唯一的,所以它只返回所有内容。在这种情况下,查询意味着“选择每个线程中每个用户的最后一篇文章”,因为线程是唯一的,所以它只返回所有内容。