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) i
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.
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 DISTINCT TOP 3 id,[Password]
FROM Users_changepassword
WHERE [UserId] = 3
ORDER BY id DESC
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.
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
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;
DBFiddle Demo
DBFiddle Demo2
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;
DBFiddle Demo3