Related
I want to get 2nd highest salary from Employee table. So please help me to find out. I tried it by using below query.
Select Max(salary) from Employee;
It gives the highest salary from salary column. But I want 2nd highest salary.
select max(sal) from
(select sal,dense_rank() over (order by sal desc) dr from emp) where dr=2;
If salaries like 5000,3000,3000,2000... Dense_rank() will give you the employees having 3000 salary
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
This gives you second highest.
Try this
DECLARE #N int
SET #N = 2 -- Change the value here to pick a different salary rank
SELECT Salary
FROM (
SELECT row_number() OVER (ORDER BY Salary DESC) as SalaryRank, Salary
FROM Salaries
) as SalaryCTE
WHERE SalaryRank = #N
Not only 2nd Salary but you can get all your desired highest salaries (like 3rd, 5th) by this query.
select salary from(select rownum rn,salary from
(select distinct(salary) from emp order by salary desc)) x where x.rn in (1,2,3);
Just Replace your desired salary position in place of (1,2,3), like (3,5), so it will give you 3rd and 5th highest salary, like:
select salary from(select rownum rn,salary from
(select distinct(salary) from emp order by salary desc)) x where x.rn in (3,5);
Below is the example
SELECT *
FROM (
SELECT column1,
row_number() over (order by salary desc) as [rownum]
From sal_table
) t
WHERE [rownum] = 2
If there is more than one row with same salary you can use dense_rank instead of row_number()
One more:
SELECT a.salary
FROM employee a
WHERE (:n - 1) = (SELECT COUNT(1)
FROM employee b
WHERE b.salary > a.salary);
Just replace n with the nth highest that you want.
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
Suppose I have a table employee with id, user_name, salary. How can I select the record with the 2nd highest salary in Oracle?
I googled it, find this solution, is the following right?:
select sal from
(select rownum n,a.* from
( select distinct sal from emp order by sal desc) a)
where n = 2;
RANK and DENSE_RANK have already been suggested - depending on your requirements, you might also consider ROW_NUMBER():
select * from (
select e.*, row_number() over (order by sal desc) rn from emp e
)
where rn = 2;
The difference between RANK(), DENSE_RANK() and ROW_NUMBER() boils down to:
ROW_NUMBER() always generates a unique ranking; if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings (randomly)
RANK() and DENSE_RANK() will give the same ranking to rows that cannot be distinguished by the ORDER BY clause
DENSE_RANK() will always generate a contiguous sequence of ranks (1,2,3,...), whereas RANK() will leave gaps after two or more rows with the same rank (think "Olympic Games": if two athletes win the gold medal, there is no second place, only third)
So, if you only want one employee (even if there are several with the 2nd highest salary), I'd recommend ROW_NUMBER().
If you're using Oracle 8+, you can use the RANK() or DENSE_RANK() functions like so
SELECT *
FROM (
SELECT some_column,
rank() over (order by your_sort_column desc) as row_rank
) t
WHERE row_rank = 2;
This query works in SQL*PLUS to find out the 2nd Highest Salary -
SELECT * FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP));
This is double sub-query.
I hope this helps you..
WITH records
AS
(
SELECT id, user_name, salary,
DENSE_RANK() OVER (PARTITION BY id ORDER BY salary DESC) rn
FROM tableName
)
SELECT id, user_name, salary
FROM records
WHERE rn = 2
DENSE_RANK()
You should use something like this:
SELECT *
FROM (select salary2.*, rownum rnum from
(select * from salary ORDER BY salary_amount DESC) salary2
where rownum <= 2 )
WHERE rnum >= 2;
select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))
so in our emp table(default provided by oracle) here is the output
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-81 3000 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
or just you want 2nd maximum salary to be displayed
select max(sal) from emp where sal<(select max(sal) from emp)
MAX(SAL)
3000
select * FROM (
select EmployeeID, Salary
, dense_rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = 2;
dense_rank() is used for the salary has to be same.So it give the proper output instead of using rank().
select Max(Salary) as SecondHighestSalary from Employee where Salary not in
(select max(Salary) from Employee)
I would suggest following two ways to implement this in Oracle.
Using Sub-query:
select distinct SALARY
from EMPLOYEE e1
where 1=(select count(DISTINCT e2.SALARY) from EMPLOYEE e2 where
e2.SALARY>e1.SALARY);
This is very simple query to get required output. However, this query is quite slow as each salary in inner query is compared with all distinct salaries.
Using DENSE_RANK():
select distinct SALARY
from
(
select e1.*, DENSE_RANK () OVER (order by SALARY desc) as RN
from EMPLOYEE e
) E
where E.RN=2;
This is very efficient query. It works well with DENSE_RANK() which assigns consecutive ranks unlike RANK() which assigns next rank depending on row number which is like olympic medaling.
Difference between RANK() and DENSE_RANK():
https://oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions
I believe this will accomplish the same result, without a subquery or a ranking function:
SELECT *
FROM emp
ORDER BY sal DESC
LIMIT 1
OFFSET 2
This query helps me every time for problems like this. Replace N with position..
select *
from(
select *
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
)
where SALARY_COLUMN <= all(
select SALARY_COLUMN
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
);
select * from emp where sal = (
select sal from
(select rownum n,a.sal from
( select distinct sal from emp order by sal desc) a)
where n = 2);
This is more optimum, it suits all scenarios...
select max(Salary) from EmployeeTest where Salary < ( select max(Salary) from EmployeeTest ) ;
this will work for all DBs.
You can use two max function. Let's say get data of userid=10 and its 2nd highest salary from SALARY_TBL.
select max(salary) from SALARY_TBL
where
userid=10
salary <> (select max(salary) from SALARY_TBL where userid=10)
Replace N with your Highest Number
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
Explanation
The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause.
And Source
I have given the answer here
By the way I am flagging this Question as Duplicate.
Syntax it for Sql server
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP n-1 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
To get 2nd highest salary of employee then we need replace “n” with 2 our query like will be this
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP 1 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
3rd highest salary of employee
SELECT MAX(Salary) as 'Salary' from EmployeeDetails
where Salary NOT IN
(
SELECT TOP 2 (SALARY) from EmployeeDetails ORDER BY Salary Desc
)
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP));
(OR)
SELECT ENAME ,SAL FROM EMP ORDER BY SAL DESC;
(OR)
SELECT * FROM(SELECT ENAME,SAL ,DENSE_RANK()
OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) R FROM EMP) WHERE R=2;
select salary from EmployeeDetails order by salary desc limit 1 offset (n-1).
If you want to find 2nd highest than replace n with that 2.
It's a question I got this afternoon:
There a table contains ID, Name, and Salary of Employees, get names of the second-highest salary employees, in SQL Server
Here's my answer, I just wrote it in paper and not sure that it's perfectly valid, but it seems to work:
SELECT Name FROM Employees WHERE Salary =
( SELECT DISTINCT TOP (1) Salary FROM Employees WHERE Salary NOT IN
(SELECT DISTINCT TOP (1) Salary FROM Employees ORDER BY Salary DESCENDING)
ORDER BY Salary DESCENDING)
I think it's ugly, but it's the only solution come to my mind.
Can you suggest me a better query?
Thank you very much.
To get the names of the employees with the 2nd highest distinct salary amount you can use.
;WITH T AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employees
)
SELECT Name
FROM T
WHERE Rnk=2;
If Salary is indexed the following may well be more efficient though especially if there are many employees.
SELECT Name
FROM Employees
WHERE Salary = (SELECT MIN(Salary)
FROM (SELECT DISTINCT TOP (2) Salary
FROM Employees
ORDER BY Salary DESC) T);
Test Script
CREATE TABLE Employees
(
Name VARCHAR(50),
Salary FLOAT
)
INSERT INTO Employees
SELECT TOP 1000000 s1.name,
abs(checksum(newid()))
FROM sysobjects s1,
sysobjects s2
CREATE NONCLUSTERED INDEX ix
ON Employees(Salary)
SELECT Name
FROM Employees
WHERE Salary = (SELECT MIN(Salary)
FROM (SELECT DISTINCT TOP (2) Salary
FROM Employees
ORDER BY Salary DESC) T);
WITH T
AS (SELECT *,
DENSE_RANK() OVER (ORDER BY Salary DESC) AS Rnk
FROM Employees)
SELECT Name
FROM T
WHERE Rnk = 2;
SELECT Name
FROM Employees
WHERE Salary = (SELECT DISTINCT TOP (1) Salary
FROM Employees
WHERE Salary NOT IN (SELECT DISTINCT TOP (1) Salary
FROM Employees
ORDER BY Salary DESC)
ORDER BY Salary DESC)
SELECT Name
FROM Employees
WHERE Salary = (SELECT TOP 1 Salary
FROM (SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary DESC) sel
ORDER BY Salary ASC)
SELECT * from Employee
WHERE Salary IN (SELECT MAX(Salary)
FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary)
FFROM employee));
Try like this..
This might help you
SELECT
MIN(SALARY)
FROM
EMP
WHERE
SALARY in (SELECT
DISTINCT TOP 2 SALARY
FROM
EMP
ORDER BY
SALARY DESC
)
We can find any nth highest salary by putting n (where n > 0) in place of 2
Example for 5th highest salary we put n = 5
How about a CTE?
;WITH Salaries AS
(
SELECT Name, Salary,
DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'SalaryRank'
FROM
dbo.Employees
)
SELECT Name, Salary
FROM Salaries
WHERE SalaryRank = 2
DENSE_RANK() will give you all the employees who have the second highest salary - no matter how many employees have the (identical) highest salary.
All of the following queries work for MySQL:
SELECT MAX(salary) FROM Employee WHERE Salary NOT IN (SELECT Max(Salary) FROM Employee);
SELECT MAX(Salary) From Employee WHERE Salary < (SELECT Max(Salary) FROM Employee);
SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1;
SELECT Salary FROM (SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT 2) AS Emp ORDER BY Salary LIMIT 1;
Another intuitive way is :-
Suppose we want to find Nth highest salary then
1) Sort Employee as per descending order of salary
2) Take first N records using rownum. So in this step Nth record here is Nth highest salary
3) Now sort this temporary result in ascending order. Thus Nth highest salary is now first record
4) Get first record from this temporary result.
It will be Nth highest salary.
select * from
(select * from
(select * from
(select * from emp order by sal desc)
where rownum<=:N )
order by sal )
where rownum=1;
In case there are repeating salaries then in innermost query distinct can be used.
select * from
(select * from
(select * from
(select distinct(sal) from emp order by 1 desc)
where rownum<=:N )
order by sal )
where rownum=1;
select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );
Simple way WITHOUT using any special feature specific to Oracle, MySQL etc.
Suppose EMPLOYEE table has data as below. Salaries can be repeated.
By manual analysis we can decide ranks as follows :-
Same result can be achieved by query
select *
from (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from
EMPLOYEE ) where distsal >tout.sal) as rank from EMPLOYEE tout
) result
order by rank
First we find out distinct salaries.
Then we find out count of distinct salaries greater than each row.
This is nothing but the rank of that id.
For highest salary, this count will be zero. So '+1' is done to start rank from 1.
Now we can get IDs at Nth rank by adding where clause to above query.
select *
from (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from
EMPLOYEE ) where distsal >tout.sal) as rank from EMPLOYEE tout
) result
where rank = N;
The simple way is to use OFFSET. Not only second, any position we can query using offset.
SELECT SALARY,NAME FROM EMPLOYEE ORDER BY SALARY DESC LIMIT 1 OFFSET 1 --Second largest
SELECT SALARY,NAME FROM EMPLOYEE ORDER BY SALARY DESC LIMIT 1 OFFSET 9 --For 10th largest
I think you would want to use DENSE_RANK as you don't know how many employees have the same salary and you did say you wanted nameS of employees.
CREATE TABLE #Test
(
Id INT,
Name NVARCHAR(12),
Salary MONEY
)
SELECT x.Name, x.Salary
FROM
(
SELECT Name, Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) as Rnk
FROM #Test
) x
WHERE x.Rnk = 2
ROW_NUMBER would give you unique numbering even if the salaries tied, and plain RANK would not give you a '2' as a rank if you had multiple people tying for highest salary. I've corrected this as DENSE_RANK does the best job for this.
Below query can be used to find the nth maximum value, just replace 2 from nth number
select * from emp e1 where 2 =(select count(distinct(salary)) from emp e2
where e2.emp >= e1.emp)
Here I used two queries for the following scenarios which are asked during an interview
First scenario:
Find all second highest salary in the table (Second highest salary with more than
one employee )
select * from emp where salary
In (select MAX(salary) from emp where salary NOT IN (Select MAX(salary) from
emp));
Second scenario:
Find only the second highest salary in the table
select min(temp.salary) from (select * from emp order by salary desc limit 2)
temp;
There are two way to do this first:
Use subquery to find the 2nd highest
SELECT MAX(salary) FROM employees
WHERE salary NOT IN (
SELECT MAX (salary) FROM employees)
But this solution is not much good as if you need to find out the 10 or 100th highest then you may be in trouble. So instead go for window function like
select * from
(
select salary,ROW_NUMBER() over(
order by Salary desc) as
rownum from employees
) as t where t.rownum=2
By using this method you can find out nth highest salary without any trouble.
select * from emp where salary = (
select salary from
(select ROW_NUMBER() over (order by salary) as 'rownum', *
from emp) t -- Order employees according to salary
where rownum = 2 -- Get the second highest salary
)
select max(age) from yd where age<(select max(age) from HK) ; /// True two table Highest
SELECT * FROM HK E1 WHERE 1 =(SELECT COUNT(DISTINCT age) FROM HK E2 WHERE E1.age < E2.age); ///Second Hightest age RT single table
select age from hk e1 where (3-1) = (select count(distinct (e2.age)) from yd e2 where e2.age>e1.age);//// same True Second Hight age RT two table
select max(age) from YD where age not in (select max(age) from YD); //second hight age in single table
Can we also use
select e2.max(sal), e2.name
from emp e2
where (e2.sal <(Select max (Salary) from empo el))
group by e2.name
Please let me know what is wrong with this approach
SELECT *
FROM TABLE1 AS A
WHERE NTH HIGHEST NO.(SELECT COUNT(ATTRIBUTE) FROM TABLE1 AS B) WHERE B.ATTRIBUTE=A.ATTRIBUTE;
this is the simple query .. if u want the second minimum then just change the max to min and change the less than(<) sign to grater than(>).
select max(column_name) from table_name where column_name<(select max(column_name) from table_name)
SELECT name
FROM employee
WHERE salary =
(SELECT MIN(salary)
FROM (SELECT TOP (2) salary
FROM employee
ORDER BY salary DESC) )
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)
If you want to display the name of the employee who is getting the second highest salary then use this:
SELECT employee_name
FROM employee
WHERE salary = (SELECT max(salary)
FROM employee
WHERE salary < (SELECT max(salary)
FROM employee);
Try This one
select * from
(
select name,salary,ROW_NUMBER() over( order by Salary desc) as
rownum from employee
) as t where t.rownum=2
http://askme.indianyouth.info/details/write-a-sql-query-to-find-the-10th-highest-employee-salary-from-an-employee-table-explain-your-answer-111
Try this to get the respective nth highest salary.
SELECT
*
FROM
emp e1
WHERE
2 = (
SELECT
COUNT(salary)
FROM
emp e2
WHERE
e2.salary >= e1.salary
)
Select * from employee where salary = (Select max(salary) from employee where salary not in(Select max(salary)from employee))
Explanation :
Query 1 : Select max(salary) from employee where salary not in(Select max(salary) from employee) - This query will retrieve second highest salary
Query 2 : Select * from employee where salary=(Query 1) - This query will retrieve all the records having second highest salary(Second highest salary may have multiple records)
I think this is probably the simplest out of the lot.
SELECT Name FROM Employees group BY Salary DESCENDING limit 2;
Try this: This will give dynamic results irrespective of no of rows
SELECT * FROM emp WHERE salary = (SELECT max(e1.salary)
FROM emp e1 WHERE e1.salary < (SELECT Max(e2.salary) FROM emp e2))**
Here's a simple approach:
select name
from employee
where salary=(select max(salary)
from(select salary from employee
minus
select max(salary) from employee));
I want to post here possibly easiest solution. It worked in mysql.
Please check at your end too:
SELECT name
FROM `emp`
WHERE salary = (
SELECT salary
FROM emp e
ORDER BY salary DESC
LIMIT 1
OFFSET 1
declare
cntr number :=0;
cursor c1 is
select salary from employees order by salary desc;
z c1%rowtype;
begin
open c1;
fetch c1 into z;
while (c1%found) and (cntr <= 1) loop
cntr := cntr + 1;
fetch c1 into z;
dbms_output.put_line(z.salary);
end loop;
end;
Using this SQL, Second highest salary will get with Employee Name
Select top 1 start at 2 salary from employee group by salary order by salary desc;
Recently in an interview I was asked to write a query where I had to fetch nth highest salary from a table without using TOP and any sub-query ?
I got totally confused as the only way I knew to implement it uses both TOP and sub-query.
Kindly provide its solution.
Thanks in advance.
Try a CTE - Common Table Expression:
WITH Salaries AS
(
SELECT
SalaryAmount, ROW_NUMBER() OVER(ORDER BY SalaryAmount DESC) AS 'RowNum'
FROM
dbo.SalaryTable
)
SELECT
SalaryAmount
FROM
Salaries
WHERE
RowNum <= 5
This gets the top 5 salaries in descending order - you can play with the RowNumn value and basically retrieve any slice from the list of salaries.
There are other ranking functions available in SQL Server that can be used, too - e.g. there's NTILE which will split your results into n groups of equal size (as closely as possible), so you could e.g. create 10 groups like this:
WITH Salaries AS
(
SELECT
SalaryAmount, NTILE(10) OVER(ORDER BY SalaryAmount DESC) AS 'NTile'
FROM
dbo.SalaryTable
)
SELECT
SalaryAmount
FROM
Salaries
WHERE
NTile = 1
This will split your salaries into 10 groups of equal size - and the one with NTile=1 is the "TOP 10%" group of salaries.
;with cte as(
Select salary,
row_number() over (order by salary desc) as rn
from salaries
)
select salary
from cte
where rn=#n
(or use dense_rank in place of row_number if you want the nth highest distinct salary amount)
Select *
From Employee E1
Where
N = (Select Count(Distinct(E2.Salary)) From Employee E2 Where E2.Salary >= E1.Salary)
with cte as(
select VendorId,IncomeDay,IncomeAmount,
Row_Number() over ( order by IncomeAmount desc) as RowNumber
from DailyIncome
)
select * from cte
where RowNumber=2
Display 5th Min Sal Emp Table.
SELECT * FROM (SELECT Dense_Rank () Over (ORDER BY Sal ASC) AS Rnk, Emp.* FROM Emp) WHERE
Rnk=5;
Try this.
SELECT * FROM
(SELECT Salary,
rownum AS roworder
FROM (select distinct Salary from employer)
ORDER BY Salary
)
where roworder = 6
;
It can simply be done as following for second highest-
Select MAX(Salary) from employer where Salary NOT IN(Select MAX(Salary) from employer);
But for Nth highest we have to use CTE(Common Table Expression).
try this. It may very easy to find nth rank items by using CTE
**
with result AS
(
SELECT *,dense_rank() over( order by Salary) as ranks FROM Employee
)
select *from RESULT Where ranks = 2
**
To find the Nth highest salary :
Table name - Emp
emplyee_id salary
1 2000
2 3000
3 5000
4 8000
5 7000
6 2000
7 1000
sql query -> here N is higest salary to be found :
select salary from (select salary from Emp order by salary DESC LIMIT N) AS E order by ASC LIMIT 1;
If there are duplicate entries of
30,000,
23,000,
23,000,
15,000,
14,800
then above selected query will not return correct output.
find correct query as below:
with salaries as
(
select Salary,DENSE_RANK() over (order by salary desc) as 'Dense'
from Table_1
)
select distinct salary from salaries
where dense=3
SELECT salery,name
FROM employ
ORDER BY salery DESC limit 1, OFFSET n
with CTE_name (salary,name)
AS
( row_num() over (order by desc salary) as num from tablename )
select salary, name from CTE_name where num =1;
This will work in oracle
In order to find the Nth highest salary, we are only considering unique salaries.Highest salary means no salary is higher than it, Second highest means only one salary is higher than it, 3rd highest means two salaries are higher than it,similarly,Nth highest salary means N-1 salaries are higher than it.
Well, you can do by using LIMIT keyword, which provides pagination
capability.You can do like below:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT N-1, 1
Ex: 2nd highest salary in MySQL without subquery:
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1,1
6- ways to write Second Highest salary..**
1.select * from employee order by Salary desc offset 1 rows fetch next 1 row only
2.select max(salary) from Employee where salary<(select max(salary) from Employee)
3.select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );
4.select max(e1.salary) from Employee e1,Employee e2 where e1.salary
5.with cte as(
SELECT *, ROW_NUMBER() OVER( order by SALARY desc) AS ROWNUM FROM EMPLOYEE as rn)
select *From cte where ROWNUM=2
6.select max(e1.Salary) from Employee e1,Employee e2 where e1.Salary
Correct way to get nth Highest salary using NTILE function.
SELECT DISTINCT SAL INTO #TEMP_A FROM EMPLOYEE
DECLARE #CNT INT
SELECT #CNT=COUNT(1) FROM #TEMP_A
;WITH RES
AS(
SELECT SAL,NTILE(#CNT) OVER (ORDER BY SAL DESC) NTL
FROM #TEMP_A )
SELECT SALFROM RES WHERE NTL=3
DROP TABLE #TEMP_A
salary ---> table name
SELECT salary
FROM salary S1
WHERE 5-1 = (
SELECT COUNT( DISTINCT ( S2.salary ) )
FROM salary S2
WHERE S2.salary > S1.salary );
Highest sal using ms sql server:
select sal from emp where sal=(select max(sal) from emp)
Second highest sal:
select max(sal) from emp where sal not in (select max(sal) from emp)
What if we are required to find Nth highest salary without Row_Number,Rank, Dense Rank and Sub Query?
Hope this below Query Helps out.
select * from [dbo].[Test] order by salary desc
Emp_Id Name Salary Department
4 Neelu 10000 NULL
2 Rohit 4000 HR
3 Amit 3000 OPS
1 Rahul 2000 IT
select B.Salary from TEst B join Test A
on B.Salary<=A.Salary
group by (B.Salary)
having count(B.salary)=2
Result:- 4000, The 2nd Highest.