1

我正在重构一位同事的代码,我有几种情况,他使用游标来获取“与某个谓词匹配的最新行”:

他的技术是将连接写成游标,按日期字段降序排列,打开游标,获取第一行,然后关闭游标。

这需要为驱动它的结果集的每一行调用一个游标,这对于许多行来说代价高昂。我更希望能够加入,但是比相关子查询更便宜:

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 分析功能可以做到这一点吗?

4

4 回答 4

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;
于 2010-04-27T02:05:16.003 回答
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;
于 2010-04-27T07:18:45.707 回答
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;
于 2010-04-27T00:54:32.937 回答
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
于 2010-04-27T06:57:01.483 回答