Can anyone please tell me how to find out the N th largest entry from a table in Oracle?
Like for largest we can use MAX(column_name) is there any efficient way to find nth largest also?
Can anyone please tell me how to find out the N th largest entry from a table in Oracle?
Like for largest we can use MAX(column_name) is there any efficient way to find nth largest also?
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
If you expect more than one row to have the same value in your_sort_column
you can also use the rank() function
SELECT * FROM ( SELECT some_column, rank() over (order by your_sort_column desc) as row_rank FROM some_table ) t WHERE row_rank = 3This migh return more than one row..
You can find the Nth largest value of a column by using the following query
SELECT *
FROM TableName a
WHERE n = (
SELECT count( DISTINCT (b.ColumnName) )
FROM TableName b
WHERE a.ColumnName <= b.ColumnName
);
I think the below query will work to find the second highest record with NOT IN.
SELECT MAX( userId )
FROM table
WHERE userId NOT IN (
SELECT MAX( userId )
FROM table
);
simple and useful...
To get second largest salary use this:
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
Try this,
SELECT Sal FROM Tab ORDER BY Sal DESC LIMIT 2,1
Try this:
SELECT DISTINCT TOP 3 id,[Password]
FROM Users_changepassword
WHERE [UserId] = 3
ORDER BY id DESC
You can try this sql where Row_number() function of the oracle sql is used
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
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)
You can ORDER BY column name
and then LIMIT 1,1
to get the second one
edit
Whoops, didn't see the Oracle tag, sorry.
ORDER BY column name WHERE ROWNUM = 2
should work better.
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (
SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal
);
Replace &N
with you desired number. For example, 2
will give you the second largest salary.
If you are using PL/SQL, just execute the statement. It will prompt for N.
You could use CONNECT BY PRIOR
by:
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;
Query:
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;
EDIT:
Second approach is to use NTH_VALUE
analytic function:
SELECT DISTINCT NTH_VALUE(sal, 2) OVER(ORDER BY sal DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM t;