任何人都可以告诉我如何找出Oracle中表中的第N个最大条目吗?
对于最大的我们可以使用 MAX(column_name)是否有任何有效的方法来找到第n个最大的?
答案 0 :(得分:19)
SELECT * FROM ( SELECT some_column, row_number() over (order by your_sort_column desc) as row_num FROM some_table ) t WHERE row_num = 3
如果您希望在your_sort_column
中有多个行具有相同的值,则还可以使用rank()函数
SELECT * FROM ( SELECT some_column, rank() over (order by your_sort_column desc) as row_rank FROM some_table ) t WHERE row_rank = 3这个migh返回多行..
答案 1 :(得分:6)
您可以使用以下查询
找到列的第n个最大值SELECT * FROM TableName a WHERE
n = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE a.ColumnName <=b.ColumnName);
答案 2 :(得分:4)
我认为以下查询可以找到NOT IN的第二高记录。
SELECT MAX(
userId
)FROM table WHERE userId
NOT IN (SELECT MAX( userId
)FROM table)
简单实用......
答案 3 :(得分:1)
获得第二大薪水使用此:
select salary from
(select s2.salary,rownum rm from
(select distinct salary from employees order by salary desc)
s2 where rownum<=2)
where rm >= 2
答案 4 :(得分:1)
它适用于第二高薪,
$query = "SELECT * FROM `table_name` ORDER BY field_name` DESC LIMIT 1 , 1 ";
答案 5 :(得分:0)
您可以ORDER BY column name
然后LIMIT 1,1
获取第二个
修改强>
哎呀,没看到Oracle标签,抱歉
ORDER BY column name WHERE ROWNUM = 2
应该会更好。
答案 6 :(得分:0)
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (
SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal
);
将&N
替换为您想要的号码。例如,2
将为您提供第二大薪水。
如果您正在使用PL / SQL,只需执行该语句即可。它会提示N.
答案 7 :(得分:0)
试试这个,
SELECT Sal FROM Tab ORDER BY Sal DESC LIMIT 2,1
答案 8 :(得分:0)
试试这个:
SELECT DISTINCT TOP 3 id,[Password]
FROM Users_changepassword
WHERE [UserId] = 3
ORDER BY id DESC
答案 9 :(得分:0)
你可以尝试使用oracle sql的Row_number()函数的这个sql
select column_name from (
select column_name ,
row_number() over (order by column_name desc) as row_num
from table_Name ) tablex
where row_num =3
答案 10 :(得分:0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="green"></div>
<div class="blue"></div>
答案 11 :(得分:0)
您可以使用CONNECT BY PRIOR
:
CREATE TABLE t(i INT, sal INT);
INSERT INTO t(i, sal)
SELECT 1,100 FROM dual UNION
SELECT 2,100 FROM dual UNION
SELECT 3,200 FROM dual UNION
SELECT 4,500 FROM dual UNION
SELECT 5,1000 FROM dual;
查询:
SELECT level, MAX(sal) AS sal
FROM t
--WHERE level = 2 -- set position here
CONNECT BY prior sal > sal
GROUP BY level
ORDER BY level;
<强> DBFiddle Demo 强>
<强> DBFiddle Demo2 强>
修改强>
第二种方法是使用NTH_VALUE
分析函数:
SELECT DISTINCT NTH_VALUE(sal, 2) OVER(ORDER BY sal DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM t;
<强> DBFiddle Demo3 强>