我正在重构一个同事的代码,我有几个案例,他使用游标来获取“匹配某个谓词的最新行”:
他的技巧是将连接写为光标,按日期字段降序排序,打开光标,获取第一行,然后关闭光标。
这需要为驱动它的结果集的每一行调用一个游标,这对很多行来说代价很高。我宁愿能够加入,但是比相关子查询更便宜的东西:
select a.id_shared_by_several_rows, a.foo from audit_trail a
where a.entry_date = (select max(a.entry_date)
from audit_trail b
where b.id_shared_by_several_rows = a.id_shared_by_several_rows
);
我猜测,因为这是一个常见的需求,有一个Oracle分析函数可以做到这一点吗?
答案 0 :(得分:2)
这只会对数据进行一次传递,并且可以根据需要从表中获取尽可能多的列而不进行自联接。
select DISTINCT
a.id_shared_by_several_rows,
FIRST_VALUE(a.foo)
OVER (PARTITION BY a.id_shared_by_several_rows
ORDER BY a.entry_date DESC)
AS foo
from audit_trail a;
答案 1 :(得分:1)
有分析RANK,DENSE_RANK和ROW_NUMBER,用于根据排序标准识别行的序列号。它们在处理顺序列中没有差异的行的方式上有所不同。 [例如,你可能得到1,1,3或1,1,2或1,2,3。]
select index_name, column_name, column_position,
rank() over (partition by table_name order by column_position) rnk,
dense_rank() over (partition by table_name order by column_position) drnk,
row_number() over (partition by table_name order by column_position) rn
from all_ind_columns
where index_owner = 'SYSMAN'
and table_name = 'MGMT_JOB_EXECUTION';
由于分析对所选行进行操作,因此您仍需要子查询/内联视图来过滤掉您不想要的行。在此示例中,INDEX_NAME是共享标识符
select index_name, column_name
from
(select index_name, column_name, column_position,
row_number() over (partition by index_name order by column_position) rn
from all_ind_columns
where index_owner = 'SYSMAN'
and table_name = 'MGMT_JOB_EXECUTION')
where rn = 1;
答案 2 :(得分:1)
我相信你想用
select
max(id_shared_by_several_rows) keep (dense_rank first order by entry_date),
max(foo ) keep (dense_rank first order by entry_date)
from
audit_trail;
答案 3 :(得分:0)
试试这个:
select id_shared_by_several_rows, foo from (
select a.id_shared_by_several_rows, a.foo, a.entry_date, max(a.entry_date) over (partition by a.id_shared_by_several_rows) max_entry_date
from audit_trail_a
) where entry_date = max_entry_date