Related
I need to write a query that will return the third highest salaried employee in the company.
I was trying to accomplish this with subqueries, but could not get the answer. My attempts are below:
select Max(salary)
from employees
where Salary not in
(select Max(salary)
from employees
where Salary not in
(select Max(salary)
from employees));
My thought was that I could use 2 subqueries to elimitate the first and second highest salaries. Then I could simply select the MAX() salary that is remaining. Is this a good option, or is there a better way to achieve this?
The most simple way that should work in any database is to do following:
SELECT * FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2;
Which orders employees by salary and then tells db to return a single result (1 in LIMIT) counting from third row in result set (2 in OFFSET). It may be OFFSET 3 if your DB counts result rows from 1 and not from 0.
This example should work in MySQL and PostgreSQL.
Edit:
But there's a catch if you only want the 3rd highest DISTINCT salary. Than you should add the DISTINCT keyword.
In case of salary list: 100, 90, 90, 80, 70.
In the above query it will produce the 3rd highest salary which is 90. But if you mean the 3rd distinct which is 80 than you should use
SELECT DISTINCT `salary` FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2;
But there's a catch, this will return you only 1 column which is Salary, because in order to operate the distinction operation, DISTINCT can only operate on a specific set of columns.
This means we should add another wrapping query to extract the employees(There can be multiple) that matches that result. Thus I added LIMIT 1 at the end.
SELECT *
FROM `employee`
WHERE
`Salary` = (SELECT DISTINCT `Salary`
FROM `employee`
ORDER BY `salary` DESC
LIMIT 1 OFFSET 2
)
LIMIT 1;
Examples can be found HERE
You can get the third highest salary by using limit , by using TOP keyword and sub-query
TOP keyword
SELECT TOP 1 salary
FROM
(SELECT TOP 3 salary
FROM Table_Name
ORDER BY salary DESC) AS Comp
ORDER BY salary ASC
limit
SELECT salary
FROM Table_Name
ORDER BY salary DESC
LIMIT 2, 1
by subquery
SELECT salary
FROM
(SELECT salary
FROM Table_Name
ORDER BY salary DESC
LIMIT 3) AS Comp
ORDER BY salary
LIMIT 1;
I think anyone of these help you.
You may try (if MySQL):
SELECT salary FROM employee ORDER BY salary DESC LIMIT 2, 1;
This query returns one row after skipping two rows.
You may also want to return distinct salary. For example, if you have 20,20,10 and 5 then 5 is the third highest salary. To do so, add DISTINCT to the above query:
SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 2, 1;
SELECT Max(salary)
FROM employee
WHERE salary < (SELECT Max(salary)
FROM employee
WHERE salary NOT IN(SELECT Max(salary)
FROM employee))
hope this helped you
If SQL Server this could work
SELECT TOP (1) * FROM
(SELECT TOP (3) salary FROM employees ORDER BY salary DESC) T
ORDER BY salary ASC
As for your number of subqueries question goes it depends on your language. Check this for more information
Is there a nesting limit for correlated subqueries in Oracle?
SELECT id
FROM tablename
ORDER BY id DESC
LIMIT 2 , 1
This is only for get 3rd highest value .
You may use this for all employee with 3rd highest salary:
SELECT * FROM `employee` WHERE salary = (
SELECT DISTINCT(`salary`) FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2
);
Some DBMS's don't allow you to run several nested queries. Here is a solution that only uses 1 nested query:
SELECT salary
FROM
(
SELECT salary
FROM employees
ORDER BY salary
LIMIT 3
) as TBL1
ORDER BY salary DESC
LIMIT 1;
It should give you the desired result. It first finds the 3 largest salaries, then selects the smallest of the three (or the third one if they are equal). Here is an SQLFiddle
I found a very good explanation in
http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/
This query should give nth highest salary
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
SELECT MAX(salary) FROM employees GROUP BY salary ORDER BY salary DESC LIMIT 1 OFFSET 2;
SELECT * FROM employee ORDER BY salary DESC LIMIT 1 OFFSET 2;
You can use nested query to get that, like below one is explained for the third max salary. Every nested salary is giving you the highest one with the filtered where result and at the end it will return you exact 3rd highest salary irrespective of number of records for the same salary.
select * from users where salary < (select max(salary) from users where salary < (select max(salary) from users)) order by salary desc limit 1
Below query will give accurate answer. Follow and give me comments:
select top 1 salary from (
select DISTINCT top 3 salary from Table(table name) order by salary ) as comp
order by personid salary
you can get any order for salary with that:
select * from
(
select salary,row_Number() over (order by salary DESC ) RN
FROM employees
)s
where RN = 3
-- put RN equal to any number of orders.
--for your question put 3
You can find Nth highest salary by making use of just one single query which is very simple to understand:-
select salary from employees e1 where N-1=(select count(distinct
salary) from employees e2 where e2.salary>e1.salary);
Here Replace "N" with number(1,2,3,4,5...).This query work properly even when where salaries are duplicate. The simple idea behind this query is that the inner subquery
count how many salaries are greater then (N-1). When we get the count then the cursor will point to that row which is N and it simply returns the salary present in that row.
SELECT salary FROM employees e1
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM employees e2
WHERE e2.salary > e1.salary)
Here, I have solved it with a correlated nested query. It is a generalized Query so if you want to print 4th, 5th, or any number of highest salary it will work perfectly even if there are any duplicate salaries.
So, what you have to do is simply change the N value here. So, in your case, it will be,
SELECT salary FROM employees e1
WHERE 3-1 = (SELECT COUNT(DISTINCT salary) FROM employees e2
WHERE e2.salary > e1.salary)
Note that the third highest salary may be the same the the first highest salary so your current approach wouldn't work.
I would do order the employees by salary and apply a LIMIT 3 at the end of the SQL query. You'll then have the top three of highest salaries and, thus, you also have the third highest salary (if there is one, a company may have two employees and then you wouldn't have a third highest salary).
For me this query work fine in Mysql
it will return third max salary from table
SELECT salary FROM users ORDER BY salary DESC LIMIT 1 OFFSET 2;
or
SELECT salary FROM users ORDER BY salary DESC LIMIT 2,1;
select min (salary) from Employee where Salary in (Select Top 3 Salary from Employee order by Salary desc)
SELECT TOP 1 BILL_AMT Bill_Amt FROM ( SELECT DISTINCT TOP 3 NH_BL_BILL.BILL_AMT FROM NH_BL_BILL ORDER BY BILL_AMT DESC) A
ORDER BY BILL_AMT ASC
SELECT DISTINCT MAX(salary) AS max
FROM STAFF
WHERE salary IN
(SELECT salary
FROM STAFF
WHERE salary<(SELECT MAX(salary) AS maxima
FROM STAFF
WHERE salary<
(SELECT MAX(salary) AS maxima
FROM STAFF))
GROUP BY salary);
I have tried other ways they are not right. This one works.
We can find the Top nth Salary with this Query.
WITH EMPCTE AS (
SELECT E.*, DENSE_RANK() OVER(ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES E
)
SELECT * FROM EMPCTE WHERE DENSERANK=&NUM
for oracle it goes like this:
select salary from employee where rownnum<=3 order by salary desc
minus
select salary from employee where rownnum<=2 order by salary desc;
The SQL-Server implementation of this will be:
SELECT SALARY FROM EMPLOYEES OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY
This is a MYSQL query.
Explanation: The subquery returns top 3 salaries. From the returned result, we select the minimum salary, which is the 3rd highest salary.
SELECT MIN(Salary)
FROM (
SELECT Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 3
) AS TopThreeSalary;
in Sql Query you can get nth highest salary
select * from(
select empname, sal, dense_rank()
over(order by sal desc)r from Employee)
where r=&n;
To find to the 2nd highest sal set n = 2
To find 3rd highest sal set n = 3 and so on.
This works fine with Oracle db.
select SAL from ( SELECT DISTINCT SAL FROM EMP ORDER BY SAL DESC FETCH FIRST 3 ROWS ONLY ) ORDER BY SAL ASC FETCH FIRST 1 ROWS ONLY
SELECT *
FROM maintable_B7E8K
order by Salary
desc limit 1 offset 2;
--Oracle SQL
with temp as (
select distinct salary from HR.EMPLOYEES
order by SALARY desc
)
select min(temp.salary) from temp
where rownum <= 3;
SELECT * FROM(
SELECT salary, DENSE_RANK()
OVER(ORDER BY salary DESC)r FROM Employee)
WHERE r=&n;
To find the 3rd highest salary set n = 3
How to find all of the fifth highest salaried employees in a single query in SQL Server
DECLARE #result bigint
SELECT TOP 5 #result = EmpID FROM Employees ORDER BY Salary DESC
SELECT #result
Above query gives me the exactly one record at the fifth highest position,
but I want all of the fifth highest salaried EmpID's in Employees table.
Above query is referenced from How to find fifth highest salary in a single query in SQL Server
In SQL Server 2005 and up, you can use one of the ranking functions to achieve this:
;WITH RankingEmployees AS
(
SELECT
EmpID,
DENSE_RANK() OVER(ORDER BY Salary DESC) 'SalaryRank'
FROM dbo.Employees
)
SELECT
*
FROM
RankingEmployees
WHERE
SalaryRank = 5
Using DENSE_RANK will give all employees of the same salary the same rank, e.g. you'll get the fifth highest salary and all employees that have that salary.
This can be done it using the Subquery also. Below sql query does the same job
SELECT TOP 1 SALARY
FROM (
SELECT DISTINCT TOP 5 SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY
You can find out more details about the same in my blog How to find nth highest salary using SQL query
Also it can be achieved through the CTE and using DENSE_RANK()
WITH RESULT AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT TOP 1 SALARY
FROM RESULT
WHERE DENSERANK = N
Just replace the N with the highest no of salary which you need to find.
SELECT *
FROM (Select * From Employee Order By salary Desc)
WHERE ROWNUM <= 5;
The inner query i.e. Select * From Employee Order By salary Desc will return all employees from the Employee table, sorted DESCENDING by the Salary column.
By using rownum, we can filter the first 5 records.
Ok I got your qns wrong.Well the following query will work.
Select *
From
(Select ename, sal,
dense_rank() over(order by sal desc) as rank
From emp)
where rank<5
order by rank;
Try it like this:
SELECT *
FROM EMPLOYEE AS EMP1
WHERE 4 =
(
SELECT count(Distint(EMP2.SALARY)
FROM EMPLOYEE AS EMP2
WHERE EMP2.SALARY> EMP1.SALARY
)
DECLARE #result bigint
SELECT TOP 5 #result = EmpID
FROM Employees
ORDER BY Salary DESC
SELECT #result
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.
what is the query to return Name and Salary of employee Having Max Salary
SELECT Name, Salary FROM Minions
WHERE Salary = (SELECT Max(Salary) FROM Minions)
Note that this will return more than one row if there is more than one employee who have the same max salary
select name, salary from (select * from salary_table order by salary desc limit 1)
SELECT FirstName, max(salary)
FROM Employees
WHERE salary = (
SELECT max(salary)
FROM employees
)
GROUP BY FirstName
working in SQL SERVER 2012
A couple of proprietary solutions
SELECT TOP 1 [WITH ties] Name, Salary
FROM employee
ORDER BY Salary DESC
SELECT Name, Salary
FROM employee
ORDER BY Salary DESC
LIMIT 1
And a standard one
WITH E AS
(
SELECT Name, Salary,
ROW_NUMBER() OVER (ORDER BY Salary DESC) RN /*Or RANK() for ties*/
FROM employee
)
SELECT Name, Salary FROM E WHERE RN=1
In case there are multiple rows with the same MAX number then you can just limit the number to desired number like this
SELECT Name, Salary FROM Minions
WHERE Salary = (SELECT Max(Salary) FROM Minions) LIMIT 1
Select e.name, e.salary from employee e where
not exists (select salary from employee e1 where e.salary < e1.salary)
This will of course return more than one record if there are multiple people with the max salary.
If you are using an oracle database and only want a single "employee" then:
SELECT MAX( name ) KEEP ( DENSE_RANK LAST ORDER BY salary ASC ) AS name,
MAX( salary ) KEEP ( DENSE_RANK LAST ORDER BY salary ASC ) AS salary
FROM Minions;
SQLFIDDLE
(kudos to Neil N for his table name)
SQL Server has a similar FIRST_VALUE (or LAST_VALUE) analytic function.
PostgreSQL also supports window functions including LAST_VALUE.
These type of queries (grouped operaions) can execute with sub query.
Example
select *from emp where sal=(max(sal)from emp)
Assuming only one employee has maximum salary
SQL Server:
select top 1 name, salary
from employee
order by salary desc
Oracle:
select name, salary
from employee
order by salary desc
limit 1
Above queries scans the table only once unlike other queries using subqueries.
How to find fifth highest salary in a single query in SQL Server
In SQL Server 2005 & 2008, create a ranked subselect query, then add a where clause where the rank = 5.
select
*
from
(
Select
SalesOrderID, CustomerID, Row_Number() Over (Order By SalesOrderID) as RunningCount
From
Sales.SalesOrderHeader
Where
SalesOrderID > 10000
Order By
SalesOrderID
) ranked
where
RunningCount = 5
These work in SQL Server 2000
DECLARE #result int
SELECT TOP 5 #result = Salary FROM Employees ORDER BY Salary DESC
Syntax should be close. I can't test it at the moment.
Or you could go with a subquery:
SELECT MIN(Salary) FROM (
SELECT TOP 5 Salary FROM Employees ORDER BY Salary DESC
) AS TopFive
Again, not positive if the syntax is exactly right, but the approach works.
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP n salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary
where n > 1 -- (n is always greater than one)
You can find any number of highest salary using this query.
To find the 5th higest salary from a database, the query is..
select MIN(esal) from (
select top 5 esal from tbemp order by esal desc) as sal
its working check it out
SELECT MIN(Salary) FROM (
SELECT TOP 2 Salary FROM empa ORDER BY Salary DESC
) AS TopFive
It's working correctly, please use it.
Can be Most easily solved by:
SELECT MIN(Salary) FROM (
SELECT Salary FROM empa ORDER BY Salary DESC limit 5
)TopFive
You can try some thing like :
select salary
from Employees a
where 5=(select count(distinct salary)
from Employees b
where a.salary > b.salary)
order by salary desc
The below query to gets the Highest salary after particular Employee name.
Just have a look into that!
SELECT TOP 1 salary FROM (
SELECT DISTINCT min(salary) salary
FROM emp where salary > (select salary from emp where empname = 'John Hell')
) a
ORDER BY salary
select * from employee2 e
where 2=(select count(distinct salary) from employee2
where e.salary<=salary)
its working
You can find it by using this query:
select top 1 salary
from (select top 5 salary
from tbl_Employee
order by salary desc) as tbl
order by salary asc