使用MAX()获取最新数据的有效方法

时间:2016-02-17 05:22:08

标签: sql oracle greatest-n-per-group

我有一张表格,用于存储特定日期货币的汇率(TBAADM.EXC)。然而,手动输入汇率,并且先前输入的错误汇率必须存档,因此由于用户错误或因为汇率在期间汇率发生变化,表格最终可能每天都有多个给定的从 - 到汇率的条目。那天。为此,我在表中有一个名为UPDATE_NO的列,表示给定条目是当天的第n个条目。例如,当天的第一个汇率条目的UPDATE_NO值为001。如果汇率已更改或输入错误,则下一个条目的值为002,依此类推。

我现在需要做的是在特定日期获得最新的汇率兑换率:

select exc_rate
from tbaadm.exc
    where bank_id = 'BANK01'
    and designation = 'REV'
    and fr_crncy_code = 'USD'
    and to_crncy_code = 'PHP'
    and rtlist_date = '10-AUG-2015'
    and update_no = --maximum

这就是我目前所拥有的,但我认为这肯定会影响我的脚本的运行时间,因为我每个记录遍历EXC表两次:

select exc_rate
    from tbaadm.exc
    where bank_id = 'BANK01'
    and designation = 'REV'
    and fr_crncy_code = 'USD'
    and to_crncy_code = 'PHP'
    and rtlist_date = '10-AUG-2015'
    and update_no = (select max(update_no) from tbaadm.exc
        where bank_id = 'BANK01'
        and designation = 'REV'
        and fr_crncy_code = 'USD'
        and to_crncy_code = 'PHP' 
        and rtlist_date = '10-AUG-2015')    

是否有更有效的方法来利用MAX()函数?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

  

只需添加我们也可以使用具有KEEP功能的分析功能   限制查询本身的输出。无需通过INLINE视图   通过这个和表现明智它更好。希望这会有所帮助。

SELECT DISTINCT exc_rate,
MAX(update_no) KEEP (DENSE_RANK FIRST
ORDER BY update_no) OVER (PARTITION BY bank_id,designation,fr_crncy_code,to_crncy_code,rtlist_date) "Max dt"
FROM tbaadm.exc
WHERE bank_id     = 'BANK01'
AND designation   = 'REV'
AND fr_crncy_code = 'USD'
AND to_crncy_code = 'PHP'
AND rtlist_date   = '10-AUG-2015' ;

答案 1 :(得分:0)

select exc_rate
from (
select exc_rate
    , ROW_NUMBER() OVER (ORDER BY update_no DESC) rnk
    from tbaadm.exc
    where bank_id = 'BANK01'
    and designation = 'REV'
    and fr_crncy_code = 'USD'
    and to_crncy_code = 'PHP'
    and rtlist_date = '10-AUG-2015'

) i
where i.rnk = 1

https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm

更新

select exc_rate
from (
select exc_rate
    , fr_crncy_code
    , ROW_NUMBER() OVER (ORDER BY update_no DESC) rnk
    from tbaadm.exc
    where bank_id = 'BANK01'
    and designation = 'REV'
    and to_crncy_code = 'PHP'
    and rtlist_date = '10-AUG-2015'

) i
where i.rnk = 1
    AND fr_crncy_code = 'usd'

答案 2 :(得分:0)

我对Avrajit Roy的脚本添加了一些更改:

SELECT MAX(exc_rate) KEEP (DENSE_RANK LAST ORDER BY update_no) as needed_rate
FROM tbaadm.exc
WHERE bank_id     = 'BANK01'
AND designation   = 'REV'
AND fr_crncy_code = 'USD'
AND to_crncy_code = 'PHP'
AND rtlist_date   = '10-AUG-2015' ;

如果您需要查找所有组的最新费率,请添加 group by 子句