在 Oracle 中选择第二大的最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8188091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select second most minimum value in Oracle
提问by ryebr3ad
I need to write a query that selects a minimum value and it's second most minimum value from a list of integers.
我需要编写一个查询来选择一个最小值,它是整数列表中第二大的最小值。
Grabbing the smallest value is obvious:
抓取最小值是显而易见的:
select min(value) from table;
But the second smallest is not so obvious.
但次小的就没有那么明显了。
For the record, this list of integers is not sequential -- the min can be 1000, and the second most min can be 10000.
作为记录,这个整数列表不是连续的——最小值可以是 1000,第二大的最小值可以是 10000。
回答by Justin Cave
Use an analytic function
使用解析函数
SELECT value
FROM (SELECT value,
dense_rank() over (order by value asc) rnk
FROM table)
WHERE rnk = 2
The analytic functions RANK
, DENSE_RANK
, and ROW_NUMBER
are identical except for how they handle ties. RANK
uses a sports-style process of breaking ties so if two rows tie for a rank of 1, the next row has a rank of 3. DENSE_RANK
gives both of the rows tied for first place a rank of 1 and then assigns the next row a rank of 2. ROW_NUMBER
arbitrarily breaks the tie and gives one of the two rows with the lowest value a rank of 1 and the other a rank of 2.
解析函数RANK
、DENSE_RANK
和ROW_NUMBER
是相同的,只是它们处理关系的方式不同。 RANK
使用体育风格的打破平局的过程,因此如果两行DENSE_RANK
并列的排名为 1,则下一行的排名为 3。 将并列第一的两行排名为 1,然后为下一行分配排名2. ROW_NUMBER
任意打破平局,并给予具有最低值的两行之一的等级为 1,另一行的等级为 2。
回答by GolezTrol
select
value
from
(select
value,
dense_rank() over (order by value) rank
from
table)
where
rank = 2
Advantage: You can get the third value just as easy, or the bottom 10 rows (rank <= 10).
优点:您可以同样轻松地获得第三个值,或后 10 行(排名 <= 10)。
Note that the performance of this query will benefit from a proper index on 'value'.
请注意,此查询的性能将受益于“值”的正确索引。
回答by JNK
SELECT MIN(value)
FROM TABLE
WHERE Value > (SELECT MIN(value) FROM TABLE)