I have tried the below query:
select empno from (
select empno
from emp
order by sal desc
)
where rownum = 2
This is not returning any records.
When I tried this query
select rownum,empno from (
select empno from emp order by sal desc)
It gives me this output:
ROWNUM EMPNO
1 7802
2 7809
3 7813
4 7823
Can anyone tell me what's the problem with my first query? Why is it not returning any records when I add the ROWNUM filter?
To explain this behaviour, we need to understand how Oracle processes
ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and
only increments the value when a row is selected; that is, when all
conditions in the WHERE clause are met. Since our condition requires
that ROWNUM is greater than 2, no rows are selected and ROWNUM is
never incremented beyond 1.
The bottom line is that conditions such as the following will work as
expected.
.. WHERE rownum = 1;
.. WHERE rownum <= 10;
While queries with these conditions will always return zero rows.
.. WHERE rownum = 2;
.. WHERE rownum > 10;
Quoted from Understanding Oracle rownum
You should modify you query in this way in order to work:
select empno
from
(
select empno, rownum as rn
from (
select empno
from emp
order by sal desc
)
)
where rn=2;
EDIT: I've corrected the query to get the rownum after the order by sal desc
In the first query, the first row will have ROWNUM = 1 so will be rejected. The second row will also have ROWNUM = 1 (because the row before was rejected) and also be rejected, the third row will also have ROWNUM = 1 (because all rows before it were rejected) and also be rejected etc... The net result is that all rows are rejected.
The second query should not return the result you got. It should correctly assign ROWNUM after ORDER BY.
As a consequence of all this, you need to use not 2 but 3 levels of subqueries, like this:
SELECT EMPNO, SAL FROM ( -- Make sure row is not rejected before next ROWNUM can be assigned.
SELECT EMPNO, SAL, ROWNUM R FROM ( -- Make sure ROWNUM is assigned after ORDER BY.
SELECT EMPNO, SAL
FROM EMP
ORDER BY SAL DESC
)
)
WHERE R = 2
The result:
EMPNO SAL
---------------------- ----------------------
3 7813
try this:
SELECT ROW_NUMBER() OVER (ORDER BY empno) AS RowNum,
empno
FROM tableName
WHERE RowNumber = 2;
Snippet From Source:
SELECT last_name FROM
(SELECT last_name, ROW_NUMBER() OVER (ORDER BY last_name) R FROM employees)
WHERE R BETWEEN 51 and 100
REFERENCE
For nth row using rownum in oracle:
select * from TEST WHERE ROWNUM<=n
MINUS
select * from TEST WHERE ROWNUM<=(n-1);
Example for second row :
select * from TEST WHERE ROWNUM<=2
MINUS
select * from TEST WHERE ROWNUM<=1;
Select * From (SELECT *,
ROW_NUMBER() OVER(ORDER BY column_name DESC) AS mRow
FROM table_name
WHERE condition) as TT
Where TT.mRow=2;
Select Second Row From a Table in Oracle
SELECT *
FROM (SELECT * FROM emp ORDER BY rownum DESC)
WHERE rownum=1
try this way it's working 100%
SQL> SELECT * FROM STUD;
RNUMBER SNAME MARKS
104 mahesh 85
101 DHANU 20
102 BHARATH 10
100 RAJ 50
103 GOPI 65
SQL> select * from(select MARKS,ROWNUM AS RS from ( select * from stud order by marks desc)) where RS=2;
MARKS RS
65 2
SQL>
select empno
from
(
select empno,rownum as rum
from emp,
order by sal desc
)
where rum=2;
You can use RANK or DENSE_RANK to achieve what you are trying to achieve here.
Try this query 100% working
Select * from(select rownum as rn,emp.* from emp) Where rn=2;
Related
This question already has answers here:
How do I limit the number of rows returned by an Oracle query after ordering?
(14 answers)
Closed 3 years ago.
I am searching for a query to find the details of highest paid employee in the entire organization. I am using oracle DB.
Queries which I tried are:
select * from EMP order by SAL desc FETCH FIRST 1ROW ONLY;
ERROR: SQL command not properly ended
select * from EMP order by SAL desc where rownum = 1;
ERROR: SQL command not properly ended
select * from EMP order by SAL desc LIMIT 0 , 1;
ERROR: SQL command not properly ended
You could use:
SELECT *
FROM (SELECT * FROM emp ORDER BY sal DESC)
WHERE ROWNUM = 1
Please note that if rows have identifical salaries, ROWNUMBER will rank them randomly. To handle ties, you could use RANK() instead (or maybe DENSE_RANK(), depending on your needs):
SELECT *
FROM (
SELECT
e.*,
RANK() OVER(ORDER BY sal DESC) rn
FROM emp
)
WHERE rn = 1
There is an issue with all three statements.
Try this:
select * from EMP order by SAL desc FETCH FIRST ROW ONLY;
or use an analytical function ROW_NUMBER:
SELECT T.* FROM
(SELECT
T.*, ROW_NUMBER() OVER(ORDER BY SAL DESC NULLS LAST) RN
FROM EMP) T
WHERE RN = 1
Cheers!!
To find out the Nth max sal in oracle i'm using below query
SELECT DISTINCE sal
FROM emp a
WHERE (
SELECT COUNT(DISTINCE sal)
FROM emp b
WHERE a.sal<=b.sal)=&n;
But According to me by using the above query it will take more time to execute if table size is big.
i'm trying to use the below query
SELECT sal
FROM (
SELECT DISTINCE sal
FROM emp
ORDER BY sal DESC )
WHERE rownum=3;
but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.
try this
select *
from
(
select
sal
,dense_rank() over (order by sal desc) ranking
from table
)
where ranking = 4 -- Replace 4 with any value of N
SELECT sal FROM (
SELECT sal, row_number() OVER (order by sal desc) AS rn FROM emp
)
WHERE rn = 3
Yes, it will take longer to execute if the table is big. But for "N-th row" queries the only way is to look through all the data and sort it. It will be definitely much faster if you have an index on sal.
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
This will show the 3rd max salary from table employee.
If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...
select min(sal) from(select distinct(sal) from emp where rownum<=3 order by sal desc);
SELECT Min(sal)
FROM (SELECT DISTINCT sal
FROM emp
WHERE sal IS NOT NULL
ORDER BY sal DESC)
WHERE rownum <= n;
These queries will also work:
Workaround 1)
SELECT ename, sal
FROM Emp e1 WHERE n-1 = (SELECT COUNT(DISTINCT sal)
FROM Emp e2 WHERE e2.sal > e1.sal)
Workaround 2) using row_num function.
SELECT *
FROM (
SELECT e.*, ROW_NUMBER() OVER (ORDER BY sal DESC) rn FROM Emp e
) WHERE rn = n;
Workaround 3 ) using rownum pseudocolumn
Select MAX(SAL)
from (
Select *
from (
Select *
from EMP
order by SAL Desc
) where rownum <= n
)
The following solution works from 12c onwards:
Select min(sal) from emp where
Sal in ( select distinct (sal) from emp order by sal desc fetch first n rows only);
Replace n as per your requirement
We could write as below mentioned also.
select min(sal) from (select sal from emp where rownum=<&n order by sal desc);
In my case this Query is successfully executed (Oracle).
select salary from
(select salary, (dense_rank()
over (order by salary desc)) R
from employees)
where R='10' group by salary;
you can replace value '10' by any value of 'n'.
SELECT sal
FROM (
SELECT empno,
deptno, sal,
dense_rank( ) over ( partition by deptno order by sal desc) NRANK
FROM emp
)
WHERE NRANK = 4
SELECT *
FROM (
SELECT empno,
deptno, sal,
dense_rank( ) over ( order by sal desc) NRANK
FROM emp
)
WHERE NRANK = 4
you can replace the 2 with your desired number
select * from ( select distinct (sal),ROW_NUMBER() OVER (order by sal desc) rn from emp ) where rn=2
Refer following query for getting nth highest salary. By this way you get nth highest salary. If you want get nth lowest salary only you need to replace DESC by ASC in the query.
Now you try this you will get for sure:
SELECT DISTINCT sal
FROM emp a
WHERE (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal<=b.sal)=&n;
For your information, if you want the nth least sal:
SELECT DISTINCT sal
FROM emp a
WHERE (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal>=b.sal)=&n;
select min(sal) from (select distinct sal from employee order by sal DESC) where rownum<=N;
place the number whatever the highest sal you want to retrieve.
Try out following:
SELECT *
FROM
(SELECT rownum AS rn,
a.*
FROM
(WITH DATA AS -- creating dummy data
( SELECT 'MOHAN' AS NAME, 200 AS SALARY FROM DUAL
UNION ALL
SELECT 'AKSHAY' AS NAME, 500 AS SALARY FROM DUAL
UNION ALL
SELECT 'HARI' AS NAME, 300 AS SALARY FROM DUAL
UNION ALL
SELECT 'RAM' AS NAME, 400 AS SALARY FROM DUAL
)
SELECT D.* FROM DATA D ORDER BY SALARY DESC
) A
)
WHERE rn = 3; -- specify N'th highest here (In this case fetching 3'rd highest)
Cheers!
select * FROM (
select EmployeeID, Salary
, dense_rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = N;
dense_rank() is used for the salary has to be same.So it give the proper output instead of using rank().
SELECT TOP (1) Salary FROM
(
SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
) AS Emp ORDER BY Salary
This is for 10th max salary, you can replace 10 with n.
This will also work :
with data as
(
select sal,rwid from (
select salary as sal,rowid as rwid from salary order by salary desc
)
where rownum < 5
)
select * from salary a
where rowid = (select min(rwid) from data)
select min(sal) from (select distinct(sal) from emp order by sal desc) where rownum <=&n;
Inner query select distinct(sal) from emp order by sal desc will give the below output as given below.
SAL
5000
3000
2975
2850
2450
1600
1500
1300
1250
1100
950
800
without distinct in the above query select sal from emp order by sal desc
output as given below.
SAL
5000
3000
3000
2975
2850
2450
1600
1500
1300
1250
1250
1100
950
800
outer query will give the 'N'th max sal (E.g) I have tried here for 4th Max sal and out put as given below.
MIN(SAL)
2850
Select min(salary) from (
select distinct(salary) from empdetails order by salary desc
) where rownum <=&rn
Just enter nth number which you want.
Try this:
SELECT min(sal) FROM (
SELECT sal FROM emp ORDER BY sal desc) WHERE ROWNUM <= 3; -- Replace 3 with any value of N
You can optimize the query using Dense_rank() function.
for Example :
select distinct salary from
( select salary ,dense_rank() over (order by salary desc) ranking
from Employee
)
where ranking = 6
Note: ranking 6 is the number of nth order.
select * from (select rownum as rownumber,emp1.* from (select * from emp order by sal desc) emp1) where rownumber = 3;
Try this one :
Select sal
From (Select rownum as rank, empno,ename,sal
From (Select *
From emp order by sal desc)
)
where rank=2;
Just add the number as rank which will give you nth highest salary.
SELECT MIN(Salary) salary
FROM (
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
)
WHERE ROWNUM <= n
ORDER BY salary ASC;
-- replace "n" from line number 7 with anything you want
select MIN(salary) from (select distinct salary from employees order by SALARY DESC) WHERE ROWNUM <= 3;
5th highest salary:
SELECT
*
FROM
emp a
WHERE
4 = (
SELECT
COUNT(DISTINCT b.sal)
FROM
emp b
WHERE
a.sal < b.sal
)
Replace 4 with any value of N.
There are three methods are there...
SELECT salary,first_name,rnk
FROM (SELECT salary,first_name,rank() over (order by salary desc nulls last) as rnk from emp) where rnk=3;
SELECT salary,first_name,rnk
FROM (SELECT salary,first_name,dense_rank() over (order by salary desc nulls last) as rnk from emp) where rnk=3;
select rnk,first_name,salary
from (select rownum as rnk ,first_name,salary
from (select first_name,salary
from emp order by salary desc nulls last)) where rnk=3
i'm using below query to retrieve even numbered records.but in reslut it is displaying no rows
select ename,job from emp where mod(rownum,2)=0;
why mod(rownum,2) is not working in where conditiom
can u please also give the query to select the odd number records
Is there anything wrong with that query?
suggetions please..
It is not working because: for the first row ROWNUM is 1 and, in this case, MOD(ROWNUM,2) is 1 and since your WHERE statement is MOD(ROWNUM,2)=0 then this reduces to 1=0 and the row is discarded. The subsequent row will then be tested against a ROWNUM of 1 (since the previous row is no longer in the output and will not have a row number), which will again fail the test and be discarded. Repeat, ad nauseum and all rows fail the WHERE test and are discarded.
If you try to get the odd rows this way using WHERE MOD(ROWNUM,2)=1 then it will return the first row only and the second, and subsequent, rows will fail the test and will never be included in the query.
As Vijaykumar Hadalgi suggests, you need to select the ROWNUM in a sub-query (where it can number all the rows without a where clause to restrict it) and then in the outer query perform the test to restrict the rows:
SELECT ename, job
FROM (
SELECT ename,
job,
ROWNUM AS row_id -- Generate ROWNUM second.
FROM (
SELECT ename, job
FROM Emp
ORDER BY ename -- ORDER BY first.
)
)
WHERE MOD( row_id, 2 ) = 0; -- Filter third.
SQLFIDDLE
Try this
To find the EVEN number of row details you can use this code.
This one is comfortable in oracle SQL as well as MySQL.
select * from (select ename,job, ROWNUM AS rn from emp) where mod(rn, 2) = 0;
To find the ODD number of row details you can use this code.
select * from (select ename,job, ROWNUM AS rn from emp) where mod(rn, 2) <> 0;
-- for selecting rows 1,3,5,7....
SELECT EMPLOYEE_ID,FIRST_NAME, LAST_NAME FROM
(
SELECT DENSE_RANK OVER(ORDER BY EMPLOYEE_ID)AS RANK, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
FROM EMPLOYEES
)
WHERE MOD(RANK,2)=1
-- for selecting rows 2,4,6,8....
SELECT EMPLOYEE_ID,FIRST_NAME, LAST_NAME FROM
(
SELECT DENSE_RANK OVER(ORDER BY EMPLOYEE_ID)AS RANK, EMPLOYEE_ID, FIRST_NAME, LAST_NAME
FROM EMPLOYEES
)
WHERE MOD(RANK,2)=0
select * from emp where empid in (select decode(mod(rownum,2),0, empid,null) from emp); --Alternate record Even numbered
Fetch even records from the table
Or You can try this:
Here The inner query will fetch all the even records primary key value and based on that we can get all those record details.
SELECT * FROM EMP WHERE EMPNO IN
(
SELECT CASE MOD(ROWNUM,2)
WHEN 0 THEN EMPNO
END
FROM EMP
);
This will fetch all the odd records
SELECT * FROM EMP WHERE EMPNO IN
(
SELECT CASE MOD(ROWNUM,2)
WHEN 1 THEN EMPNO
END
FROM EMP
);
this will do :
Select * from (Select rownum as No_of_Row, E.* from emp E)
Where mod(No_of_Row,2)=0;
Use the below query u will get the result:
SELECT empno,ename,slno
FROM ( SELECT empno,ename,ROW_NUMBER() OVER
(ORDER BY empno desc) AS slno FROM emp ) result WHERE mod(slno,2) = 1;
Use the below query,
select * from (select ename,job, ROWNUM as row_id from emp) where mod(row_id, 2) = 0;
Select ename, job from emp where mod(id, 2) =0 ;
You can Try the id column intead of rownum if table has an identity column
We can use with clause
Example:
WITH Tab AS(select mod(rownum,2) AS R ,EMPLOYEES.* from employees)
SELECT * FROM Tab WHERE R = 0;
If you want odd rows then R = 1.
Example:
WITH Tab AS(select mod(rownum,2) AS R ,EMPLOYEES.* from employees)
SELECT * FROM Tab WHERE R = 1;
row num represents row number in the results table not in the original table.
So, first assign it to row_id or any variable and use that variable.
Please try :
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
Output:-
2
4
6
Select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
Output: 1,3,5..
Or this will work
this :
odd :
select * from
(
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber',
FROM table1
) d
where (RowNumber % 2) = 1
even :
select * from
(
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber',
FROM table1
) d
where (RowNumber % 2) = 0
I want to write a query to display employees getting top 3 salaries
SELECT *
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary desc)
WHERE rownum <= 3;
But I dont understand how this rownum is calculated for the nested query
will this work or if it has problem ,request you to please make me understand:
SELECT *
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary )
WHERE rownum >= 3;
I went through this link Oracle/SQL: Why does query "SELECT * FROM records WHERE rownum >= 5 AND rownum <= 10" - return zero rows ,but it again points to a link, which does not gives the answer
a_horse_with_no_name's answer is a good one,
but just to make you understand why you're 1st query works and your 2nd doesn't:
When you use the subquery, Oracle doesn't magically use the rownum of the subquery, it just gets the data ordered so it gives the rownum accordingly, the first row that matches criteria still gets rownum 1 and so on. This is why your 2nd query still returns no rows.
If you want to limit the starting row, you need to keep the subquery's rownum, ie:
SELECT *
FROM (SELECT * , rownum rn
FROM (SELECT salary, first_name
FROM employees
ORDER BY salary ) )sq
WHERE sq.rn >= 3;
But as a_horse_with_no_name said there are better options ...
EDIT: To make things clearer, look at this query:
with t as (
select 'a' aa, 4 sal from dual
union all
select 'b' aa, 1 sal from dual
union all
select 'c' aa, 5 sal from dual
union all
select 'd' aa, 3 sal from dual
union all
select 'e' aa, 2 sal from dual
order by aa
)
select sub.*, rownum main_rn
from (select t.*, rownum sub_rn from t order by sal) sub
where rownum < 4
note the difference between the sub rownum and the main rownum, see which one is used for criteria
The "rownum" of a query is assigned before an order by is applied to the result. So the rownumw 42 could wind up being the first row.
Generally speaking you need to use the rownum from the inner query to limit your overall output. This is very well explained in the manual:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/pseudocolumns009.htm#i1006297
I prefer using row_number() instead, because you have much better control over the sorting and additionally it's a standard feature that works on most modern DBMS:
SELECT *
FROM (
SELECT salary,
first_name,
row_number() over (order by salary) as rn
FROM employees
)
WHERE rn <= 3
ORDER BY salary;
You should understand that the derived table in this case is only necessary to be able to apply a condition on the generated rn column. It's not there to avoid the "rownum problem" as the value of row_number() only depends on the order specifiy in the over(...) part (it is independent of any ordering applied to the query itself)
Note this would not return employees that have the same salary and would still fall under the top three. In that case using dense_rank() is probably more approriate.
if you want to select the people with the top 3 salaries.. perhaps you should consider using analytics.. something more like
SELECT *
FROM (
SELECT salary, first_name, dense_rank() over(order by salary desc) sal_rank
FROM employees
)
WHERE sal_rank <= 3
ie ALL people with the 3rd highest(ranked) salary amount(or more)
the advantage of this over using plain rownum is if you have multiple people with the same salary they will all be returned.
Easiest way to print 5th highest salary.
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 5
according to same if u want to print 3rd or 4th highest salary then just chage last value.(means instead of 5 use 3 or 4 you will get 3rd or 4th highest salary).
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 4
SELECT MIN(SALARY) FROM (SELECT SALARY FROM EMPLOYEES ORDER BY DESC) WHERE ROWNUM BETWEEN 1 AND 3
SELECT EMPNO,
SAL,
(SELECT SUM(E.SAL) FROM TEST E WHERE E.EMPNO <= T.EMPNO) R_SAL
FROM (SELECT EMPNO, SAL FROM TEST ORDER BY EMPNO) T
Easiest way to find the top 3 employees in oracle returning all fields details:
SELECT *
FROM (
SELECT * FROM emp
ORDER BY sal DESC)
WHERE rownum <= 3 ;
select *
from (
select emp.*,
row_number() over(order by sal desc)r
from emp
)
where r <= 3;
SELECT Max(Salary)
FROM Employee
WHERE Salary < (SELECT Max(salary) FROM employee WHERE Salary NOT IN (SELECT max(salary) FROM employee))
ORDER BY salary DESC;
I want to find 2nd, 3rd, ... nth maximum value of a column.
Consider the following Employee table with a single column for salary.
+------+
| Sal |
+------+
| 3500 |
| 2500 |
| 2500 |
| 5500 |
| 7500 |
+------+
The following query will return the Nth Maximum element.
select SAL from EMPLOYEE E1 where
(N - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
For eg. when the second maximum value is required,
select SAL from EMPLOYEE E1 where
(2 - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
+------+
| Sal |
+------+
| 5500 |
+------+
You didn't specify which database, on MySQL you can do
SELECT column FROM table ORDER BY column DESC LIMIT 7,10;
Would skip the first 7, and then get you the next ten highest.
You could sort the column into descending format and then just obtain the value from the nth row.
EDIT::
Updated as per comment request. WARNING completely untested!
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
Something like the above should work for Oracle ... you might have to get the syntax right first!
Again you may need to fix for your database, but if you want the top 2nd value in a dataset that potentially has the value duplicated, you'll want to do a group as well:
SELECT column
FROM table
WHERE column IS NOT NULL
GROUP BY column
ORDER BY column DESC
LIMIT 5 OFFSET 2;
Would skip the first two, and then will get you the next five highest.
Pure SQL (note: I would recommend using SQL features specific to your DBMS since it will be likely more efficient). This will get you the n+1th largest value (to get smallest, flip the <). If you have duplicates, make it COUNT( DISTINCT VALUE )..
select id from table order by id desc limit 4 ;
+------+
| id |
+------+
| 2211 |
| 2210 |
| 2209 |
| 2208 |
+------+
SELECT yourvalue
FROM yourtable t1
WHERE EXISTS( SELECT COUNT(*)
FROM yourtable t2
WHERE t1.id <> t2.id
AND t1.yourvalue < t2.yourvalue
HAVING COUNT(*) = 3 )
+------+
| id |
+------+
| 2208 |
+------+
(Table Name=Student, Column Name= mark)
select * from(select row_number() over (order by mark desc) as t,mark from student group by mark) as td where t=4
You can find the nth largest value of 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);
select column_name from table_name
order by column_name desc limit n-1,1;
where n = 1, 2, 3,....nth max value.
Here's a method for Oracle. This example gets the 9th highest value. Simply replace the 9 with a bind variable containing the position you are looking for.
select created from (
select created from (
select created from user_objects
order by created desc
)
where rownum <= 9
order by created asc
)
where rownum = 1
If you wanted the nth unique value, you would add DISTINCT on the innermost query block.
Just dug out this question when looking for the answer myself, and this seems to work for SQL Server 2005 (derived from Blorgbeard's solution):
SELECT MIN(q.col1) FROM (
SELECT
DISTINCT TOP n col1
FROM myTable
ORDER BY col1 DESC
) q;
Effectively, that is a SELECT MIN(q.someCol) FROM someTable q, with the top n of the table retrieved by the SELECT DISTINCT... query.
Select max(sal)
from table t1
where N (select max(sal)
from table t2
where t2.sal > t1.sal)
To find the Nth max sal.
SELECT * FROM tablename
WHERE columnname<(select max(columnname) from tablename)
order by columnname desc limit 1
This is query for getting nth Highest from colomn put n=0 for second highest and n= 1 for 3rd highest and so on...
SELECT * FROM TableName
WHERE ColomnName<(select max(ColomnName) from TableName)-n order by ColomnName desc limit 1;
Simple SQL Query to get the employee detail who has Nth MAX Salary in the table Employee.
sql> select * from Employee order by salary desc LIMIT 1 OFFSET <N - 1>;
Consider table structure as:
Employee (
id [int primary key auto_increment],
name [varchar(30)],
salary [int] );
Example:
If you need 3rd MAX salary in the above table then, query will be:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 2;
Similarly:
If you need 8th MAX salary in the above table then, query will be:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 7;
NOTE:
When you have to get the Nth MAX value you should give the OFFSET as (N - 1).
Like this you can do same kind of operation in case of salary in ascending order.
mysql query:
suppose i want to find out nth max salary form employee table
select salary
form employee
order by salary desc
limit n-1,1 ;
In SQL Server, just do:
select distinct top n+1 column from table order by column desc
And then throw away the first value, if you don't need it.
for SQL 2005:
SELECT col1 from
(select col1, dense_rank(col1) over (order by col1 desc) ranking
from t1) subq where ranking between 2 and #n
MySQL:
select distinct(salary) from employee order by salary desc limit (n-1), 1;
Answer :
top second:
select * from (select * from deletetable where rownum <=2 order by rownum desc) where rownum <=1
select sal,ename from emp e where
2=(select count(distinct sal) from emp where e.sal<=emp.sal) or
3=(select count(distinct sal) from emp where e.sal<=emp.sal) or
4=(select count(distinct sal) from emp where e.sal<=emp.sal) order by sal desc;
I think that the query below will work just perfect on oracle sql...I have tested it myself..
Info related to this query : this query is using two tables named employee and department with columns in employee named: name (employee name), dept_id (common to employee and department), salary
And columns in department table: dept_id (common for employee table as well), dept_name
SELECT
tab.dept_name,MIN(tab.salary) AS Second_Max_Sal FROM (
SELECT e.name, e.salary, d.dept_name, dense_rank() over (partition BY d.dept_name ORDER BY e.salary) AS rank FROM department d JOIN employee e USING (dept_id) ) tab
WHERE
rank BETWEEN 1 AND 2
GROUP BY
tab.dept_name
thanks
Another one for Oracle using analytic functions:
select distinct col1 --distinct is required to remove matching value of column
from
( select col1, dense_rank() over (order by col1 desc) rnk
from tbl
)
where rnk = :b1
Select min(fee)
from fl_FLFee
where fee in (Select top 4 Fee from fl_FLFee order by 1 desc)
Change Number four with N.
You can simplify like this
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT TOP 4 Sal FROM TableName ORDER BY Sal DESC)
If the Sal contains duplicate values then use this
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT distinct TOP 4 Sal FROM TableName ORDER BY Sal DESC)
the 4 will be nth value it may any highest value such as 5 or 6 etc.
(TableName=Student, ColumnName=Mark) :
select *
from student
where mark=(select mark
from(select row_number() over (order by mark desc) as t,
mark
from student group by mark) as td
where t=2)
In PostgreSQL, to find N-th largest salary from Employee table.
SELECT * FROM Employee WHERE salary in
(SELECT salary FROM Employee ORDER BY salary DESC LIMIT N)
ORDER BY salary ASC LIMIT 1;
Solution to find Nth Maximum value of a particular column in SQL Server:
Employee table:
Sales table:
Employee table data:
==========
Id name
=========
6 ARSHAD M
7 Manu
8 Shaji
Sales table data:
=================
id emp_id amount
=================
1 6 500
2 7 100
3 8 100
4 6 150
5 7 130
6 7 130
7 7 330
Query to Find out details of an employee who have highest sale/ Nth highest salesperson
select * from (select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name ) AS T1 WHERE(0)=( select COUNT(DISTINCT(total_amount)) from(select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name )AS T2 WHERE(T1.total_amount<T2.total_amount) );
In the WHERE(0) replace 0 by n-1
Result:
========================
id name total_amount
========================
7 Manu 690
Table employee
salary
1256
1256
2563
8546
5645
You find the second max value by this query
select salary
from employee
where salary=(select max(salary)
from employee
where salary <(select max(salary) from employee));
You find the third max value by this query
select salary
from employee
where salary=(select max(salary)
from employee
where salary <(select max(salary)
from employee
where salary <(select max(salary)from employee)));