SQL查询子查询(第二级)

时间:2018-09-14 13:46:58

标签: sql oracle

我有一个引发级别错误的查询。该表具有两个方向的汇率

currency_from | currency_to | convertion rate
        ARS   |   USD       | 0.20
        USD   |   ARS       | 20.00

我想买一款游戏,例如,价值最高的一款游戏

currency_from | currency_to | convertion rate
        USD   |   ARS       | 20.00

在表中,很明显,有很多不同货币的组合,下面的查询可以解决问题,但没有达到第二级

select *
from gl.gl_daily_rates gdr
where  gdr.conversion_date = to_date('20180301','YYYYMMDD')
and    gdr.conversion_rate = (select max(total.conversion_rate)
                              from   (select gdr2.conversion_rate
                                      from   gl.gl_daily_rates gdr2
                                      where  gdr2.conversion_date = gdr.conversion_date
                                      and    gdr2.from_currency   = gdr.from_currency
                                      and    gdr2.to_currency     = gdr.to_currency
                                      union all
                                      select gdr3.conversion_rate
                                      from   gl.gl_daily_rates gdr3
                                      where  gdr3.conversion_date = gdr.conversion_date
                                      and    gdr3.from_currency   = gdr.to_currency
                                      and    gdr3.to_currency     = gdr.from_currency
                                      ) total);

有人认为如何解决吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以为此使用窗口功能:

select *
from (select gdr.*,
             max(conversion_rate) over (partition by least(currency_from, currency_to), greatest(currency_from, currency_to) ) as max_cr
      from gl.gl_daily_rates gdr
      where gdr.conversion_date = to_date('20180301','YYYYMMDD') 
     ) gdr
where conversion_rate = max_cr;