我需要从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
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函数吗?我知道如何处理一个文档,但无法弄清楚如何处理多个文档。
答案 0 :(得分:3)
您应该可以使用row_number()
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;