Sql Oracle查询:为每个文档获取两条最近的记录
我需要从Oracle数据库中获取每个文档的两个最新注释。 查询是:Sql Oracle查询:为每个文档获取两条最近的记录,sql,oracle,syntax,oracle-sqldeveloper,Sql,Oracle,Syntax,Oracle Sqldeveloper,我需要从Oracle数据库中获取每个文档的两个最新注释。 查询是: select a.doc_id, b.notes, b.post_ts from tableA a, tableB b where a.doc_id=b.doc_id(+) order by doc_id, post_ts desc doc_id notes post_ts 5743 Test 1 23-Aug-2010 10:25:03 5743 Test 2 14-Aug-2010 14:11:59
select a.doc_id, b.notes, b.post_ts
from tableA a, tableB b
where a.doc_id=b.doc_id(+)
order by doc_id, post_ts desc
doc_id notes post_ts
5743 Test 1 23-Aug-2010 10:25:03
5743 Test 2 14-Aug-2010 14:11:59
5743 Test 3 14-Aug-2010 13:56:20
6813 Test 4 12-Oct-2010 14:34:37
7543 Test 5 22-Apr-2014 17:02:23
7543 Test 6 22-Apr-2014 09:46:33
7543 Test 7 14-Mar-2014 12:17:58
结果应该是:
doc_id notes post_ts
5743 Test 1 23-Aug-2010 10:25:03
5743 Test 2 14-Aug-2010 14:11:59
6813 Test 4 12-Oct-2010 14:34:37
7543 Test 5 22-Apr-2014 17:02:23
7543 Test 6 22-Apr-2014 09:46:33
我可以只编写一个sql来处理这种情况,还是必须编写一个PL/sql函数?我知道如何处理一个文档,但不知道如何处理多个文档 您应该能够使用
行编号()来完成此操作。
如果您想要2个最新的注释,为什么要使用外部联接?为了为一个文档id带回2个最新注释,必须有以开头的注释。谢谢Laurence,我得到了我需要的。@tigerpuzzle,如果它解决了您的问题,请将其标记为答案,以便将来的读者可以清楚地看到。
with x as (
select
a.doc_id,
b.notes,
b.post_ts,
row_number() over (partition by a.doc_id order by b.post_ts desc) rn
from
tableA a
left outer join
tableB b
on a.doc_id = b.doc_id
) select
x.doc_id,
x.notes,
x.post_ts
from
x
where
rn in (1, 2)
order by
x.doc_id,
x.post_ts desc;