我需要从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函数?我知道如何处理一个文档,但不知道如何处理多个文档。
发布于 2014-09-05 22:20:44
您应该能够使用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;
https://stackoverflow.com/questions/25694724
复制相似问题