如何从表中获得最大的差异

时间:2014-09-08 18:04:14

标签: sql oracle

我有下表(货币):

___________________________
|symbol|rate   |Date      |
---------------------------
|USD   |1.23   |2014-09-08|
|JPY   |136.27 |2014-09-08|
|BGN   |1.9558 |2014-09-08|
|USD   |1.22   |2014-09-07|
|JPY   |136.23 |2014-09-07|
|BGN   |1.9551 |2014-09-07|

这样的事情。如何获得最高货币汇率差异(最大(汇率)-min(汇率))。我提出这样的事情:

SELECT *
FROM (SELECT c.symbol, MAX(c.rate) - MIN(c.rate) AS diff
   FROM Currency c 
   GROUP BY c.symbol
   ORDER BY diff DESC)
WHERE ROWNUM=1;

以上查询生成变化率最高的货币。它返回排序的第一行。但是,即使有两种或更多货币的变化率与最高货币相同,我也需要列出。

任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:2)

您可以通过多种方式完成此操作。这是一种使用rank()的方式:

SELECT c.*
FROM (SELECT c.symbol, MAX(c.rate) - MIN(c.rate) AS diff,
             rank() over (order by MAX(c.rate) - MIN(c.rate) DESC) as seqnum
      FROM Currency c 
      GROUP BY c.symbol
     ) c
WHERE seqnum = 1;