Let us say, I want to find the second highest salary. For that I use the following query.
select b.Salary as SecondHighestSalary from
(
select Salary, rank() over (order by Salary desc) as r
FROM Employee
) b
WHERE b.r = 2;
However, I want this to return null when the table only contains one entry, and therefore there is no 2nd highest salary. How can I do that?
Use your query with aggregation:
select max(Salary) as SecondHighestSalary
from (
select Salary, rank() over (order by Salary desc) as r
FROM Employee
) t
where r > 1;
The aggregate function max() will return null in case there is no 2nd highest salary.
One method would be:
select (select distinct salary
from employee
order by salary desc
limit 1 offset 1
);
The subquery returns NULL if the select distinct only returns one row.
With your structure, you can use conditional aggregation:
select max(case when seqnum = 2 then e.Salary end) as SecondHighestSalary
from (select Salary,
rank() over (order by Salary desc) as seqnum
from Employee e
) e;
Another easy hack with combination of union and limit.Below query will return null for no rows as well as single row.For more than one row it returns second largest salary.
select * from
(
select b.Salary as SecondHighestSalary from
(
select Salary, rank() over (order by Salary desc) as r
FROM Employee
) b
WHERE b.r = 2
union
select null) tab limit 1;
Refer DB Huddle link for full solution -https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8b8b537160ca61e29da39a4662151217
Limit it to 1 result with rank of 1 or 2 and see if the rank is 2?
select if(c.r=2,c.Salary,NULL) SecondHighestSalary
from (
select b.Salary, b.r
from (
select Salary, rank() over (order by Salary desc) as r
FROM Employee
) b
where b.r <= 2
order by b.r
limit 1
) c
Even that will not return any results if there are no entries in Employee. If you want NULL in that case too, do:
select c.SecondHighestSalary
from (select 1) dummy
left join (
select b.Salary as SecondHighestSalary from
(
select Salary, rank() over (order by Salary desc) as r
FROM Employee
) b
WHERE b.r = 2
) c;
You can use the following:
WITH cteDesired_rank(desired_rank)
AS (SELECT 2)
select DISTINCT b.Salary as SecondHighestSalary
from cteDesired_rank rr
LEFT OUTER JOIN (select Salary, rank() over (order by Salary desc) as r
FROM employee) b
ON b.r = rr.desired_rank
WHERE rr.desired_rank = 2
Here we use a common table expression to specify the rank number that we want. We select first from the common table expression because we know that our desired rank number will be present. We then outer join to the rank subquery from employee where the desired rank number might be present, but is not required to be. We then filter for desired_rank = 2 - the desired_rank value will always be present, but the calculated rank value may not be. As such, if the subquery returns rows with the desired rank they will be displayed, but if the subquery does not return rows with the desired rank value the desired rank from the common table expression will still be returned, but the salary value will be NULL.
db<>fiddle here
Related
Can anyone explain how does this two queries work ?
Q) Write a query to retrieve two minimum and maximum salaries from the EmployeePosition table.
To retrieve two minimum salaries, you can write a query as below:
A)To retrieve two minimum salaries, you can write a query as below:
SELECT DISTINCT Salary
FROM EmployeePosition E1
WHERE 2 >= (SELECT COUNT(DISTINCT Salary )
FROM EmployeePosition E2
WHERE E1.Salary >= E2.Salary
) ORDER BY E1.Salary DESC;
To retrieve two maximum salaries, you can write a query as below:
SELECT DISTINCT Salary
FROM EmployeePosition E1
WHERE 2 >= (SELECT COUNT(DISTINCT Salary)
FROM EmployeePosition E2
WHERE E1.Salary <= E2.Salary
)
ORDER BY E1.Salary DESC;
Reference table
is there any alternative SQL query to get the same result?
The question is different from what you have asked
Q21. Write a query to find the Nth highest salary from the table
without using TOP/limit keyword.
That is the second highest salary and it can be done by using row_number supported on MySQL 8.x
WITH max_salary AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM EmployeePosition
)
SELECT max_salary.*
FROM max_salary
WHERE Rnk=2;
MySQL DENSE_RANK Function assigns a rank to each row within a partition or result set (in your case it is a result set) with no gaps in ranking values.
Meaning the same salary will have the same rank.
For example using the data on the linked question:
create table EmployeePosition (
EmpID int,
EmpPosition varchar(25),
DateOfJoining date ,
Salary int );
insert into EmployeePosition values
(1,'Manager','2022-05-01',500000),
(2,'Executive','2022-05-02',75000),
(3,'Manager','2022-05-01',90000),
(2,'Lead','2022-05-02',85000),
(1,'Executive','2022-05-01',300000),
(3,'Manager','2022-05-01',500000);
SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM EmployeePosition
Result:
EmpID EmpPosition DateOfJoining Salary Rnk
1 Manager 2022-05-01 500000 1
3 Manager 2022-05-01 500000 1
1 Executive 2022-05-01 300000 2
3 Manager 2022-05-01 90000 3
2 Lead 2022-05-02 85000 4
2 Executive 2022-05-02 75000 5
As you can see each Salary is assigned a rank you have two 500000 salary with rank 1 , so the second highest value is 300000 which is filtered on the WHERE Rnk=2;.
The above main query could be written differently:
select EmpID,EmpPosition,DateOfJoining,Salary
from ( SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM EmployeePosition
) as tbl
WHERE Rnk=2;
https://dbfiddle.uk/Meh2AloO
Can you please explain the sql queries in the question?
Let's explain below example
SELECT DISTINCT Salary
FROM EmployeePosition E1
WHERE 2 >= ( SELECT COUNT(DISTINCT Salary )
FROM EmployeePosition E2
WHERE E1.Salary <= E2.Salary
)
ORDER BY E1.Salary DESC;
This is known as Correlated subqueries, which are the one in which inner query or subquery reference outer query. Outer query needs to be executed before inner query.
For each record processed by outer query, inner query will be executed and will return how many records has records has salary less than the current salary. If you are looking for second highest salary then your query will stop as soon as inner query will return 2.
I think your answer would be:
By the inner selection, I mean:
(SELECT COUNT(DISTINCT Salary)
FROM EmployeePosition E2
WHERE E1.Salary <= E2.Salary
)
The system checks all the states which each salary is greater/less than how many salaries of the rest of the list(Salary list). In another word the system calculates it for all the rows and for each row it returns the number which says that this salary value is greater/less than how many salaries.
Imagine we have distinguish values in rows and they are sorted descending, so when it checks for the highest salary it returns the total row number as a result because it calculates that there are total row number states which the salary is less and equal to the highest salary.
In the same way, For the lowest salary we will only have 1 state which the salary is equal to itself.
So when the system checks for this logic:
WHERE 2 >= (SELECT COUNT(DISTINCT Salary)
FROM EmployeePosition E2
WHERE E1.Salary <= E2.Salary
)
it looks up for the situations that the salary is greater/less and equal to 2 other salaries and by the outer selection it returns the value of salaries.
I think that is really time consuming especially when dealing with large databases. As an alternative you can use this code:
SELECT
Salary, Rank
FROM(
SELECT
Salary,
Rank= ROW_NUMBER() OVER(ORDER BY(Salary) DESC)
FROM EmployeePosition
) X
WHERE Rank<=2
I'm trying to solve the LeetCode problem https://leetcode.com/problems/second-highest-salary/description/; my solution so far (see also http://sqlfiddle.com/#!9/4752cb/1) is:
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1;
The problem is that my solution is failing on the following test case:
In other words, it is simply returning no results rather than returning NULL. How can I make it return NULL if there is no second-highest salary?
Update
Following Return a value if no record is found, I tried to encapsulate the query in a sub-query:
SELECT (SELECT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
However, this fails on a different test case in which there are two employees with the same salary:
In this case, we are apparently also supposed to return NULL. How can I adapt the 'closer to a solution' query above to handle this?
Here is a query which finally passes the tests:
SELECT (SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
It seems more intuitive than the other solutions, no?
Select another row that returns null, using union all so order is preserved, then return only the first row of that:
SELECT * FROM
(
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1
UNION ALL
SELECT NULL
)
LIMIT 1
Here OFFSET 1 means without 1st one (EX:if you don't want to display first 2 then OFFSET will be 2)
SELECT
Salary AS SecondHighestSalary
FROM
Employee
ORDER BY
Salary
LIMIT 1 OFFSET 1;
With the current query, we could just wrap it in another query, and use an aggregate function
SELECT MAX(v.salary) AS SecondHighestSalary
FROM (
SELECT e.Salary
FROM Employee e
ORDER BY e.Salary DESC
LIMIT 1, 1
) v
What should second highest salary be given this set ...
id salary
-- ------
1 1000
2 1000
4 750
Should we return 1000, or return 750? If we want to return 750, we could do something like this:
SELECT MAX(s.salary) AS SecondHighestSalary
FROM ( SELECT MAX(e.salary) AS max_salary
FROM Employee e
) h
JOIN Employee s
ON s.salary < h.max_salary
Use IFNULL :
SELECT
IFNULL( (
SELECT DISTINCT
`salary`
FROM
`Employee`
ORDER BY
`salary` DESC LIMIT 1, 1), NULL )
)
AS `SecondHighestSalary`
Returns NULL if first query returns nothing.
Safe with Distinct excluding null values:
SELECT distinct Salary AS SecondHighestSalary
FROM Employee where salary is not null ORDER BY salary desc limit 1,1
you can first get the top two values
then handle the case of null and the normal case separately
select case
when min(top2.salary)=max(top2.salary) then null
else min(top2.salary) end
as SecondHighestSalary
from
(select e.salary from employee e order by e.salary desc limit 2) as top2;
Suppose we have one table called emp that has only one column called salary that has 6 rows only.
I want the result that add the (difference of second highest and third highest salary) and (difference of fourth highest and fifth highest salary).
Note: I don't want to use any inner query for that. so please help me to write this query ?
Thanks in advance
Please find table below : (this table is not in sorted order)
|Salary|
--------
|150000|
|130000|
|140000|
|160000|
|180000|
|190000|
I have wrote this following query that given the data but as data is not in sorted order so i am facing the issue
ABS(ABS((select salary
from EMP where rownum <3 minus select salary from EMP
where rownum <2 )-
(select salary
from EMP where rownum <2 minus select salary from EMP
where rownum <1))-
ABS((select salary
from EMP where rownum <5 minus select salary from EMP
where rownum <4 )-
(select salary
from EMP where rownum <4 minus select salary from EMP
where rownum <3 )))
For Oracle:
Hard to do without subqueries... unless you are looking for really ugly and inefficient code.
Here is a neat way to do it without subqueries, in Oracle 12.1 and higher, using the match_recognize clause:
with
emp ( salary ) as (
select 150000 from dual union all
select 130000 from dual union all
select 140000 from dual union all
select 160000 from dual union all
select 180000 from dual union all
select 190000 from dual
)
-- End of simulated inputs (for testing only, not part of the solution!)
-- SQL query begins BELOW THIS LINE.
select result
from emp
match_recognize (
order by salary desc
measures (b.salary - c.salary) + (d.salary - e.salary) as result
one row per match
pattern ( ^ a b c d e )
define a as 0 = 0
)
;
RESULT
------
30000
And here is an elementary (and stupid!) way to do it:
select max(e2.salary) - max(e3.salary) + max(e4.salary) - max(e5.salary) as result
from emp e1 join emp e2 on e1.salary > e2.salary
join emp e3 on e2.salary > e3.salary
join emp e4 on e3.salary > e4.salary
join emp e5 on e4.salary > e5.salary
;
You may use NTH_VALUE Oracle function.
SELECT distinct ((NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) -
(NTH_VALUE(salary, 3) OVER (ORDER BY salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))) +
((NTH_VALUE(salary, 4) OVER (ORDER BY salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) -
(NTH_VALUE(salary, 5) OVER (ORDER BY salary DESC RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)))
FROM emp
I have an employee table in MySQL with below entries. I need to find all the employees having second highest salaries. In this case, it would be c and d.
id | name | salary
1 | a | 1000
2 | b | 1000
3 | c | 500
4 | d | 500
5 | e | 400
I tried running below query
SELECT name, MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) from employee);
But this query returns just c as a result. How to get both c and d in result?
I looked at bunch of similar questions posted but none of them mentioned how to get multiple rows for second highest salary.
You can esily get second highest salary from table
SELECT MAX(salary) FROM Employee WHERE Salary NOT IN ( SELECT Max(Salary) FROM Employee);
You can find the second highest salary with:
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1, 1
Then either feed the result of that to another query in the same transaction:
SELECT *
FROM employee
WHERE salary = ?
Or do it as a subquery:
SELECT *
FROM employee
WHERE salary = (
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1, 1
)
In case you want migrate to MSSQL Server :).
SELECT * FROM (
SELECT MAX(salary) T,RANK() OVER (ORDER BY SALARY DESC) AS RankBySalary FROM Employees
GROUP BY SALARY ) TB
WHERE RankBySalary = 3
Or much better:
SELECT * FROM
(
SELECT ID,NAME,SALARY,DENSE_RANK() OVER (ORDER BY SALARY DESC) AS RankBySalary FROM employee
)
TB WHERE RankBySalary = 2
SELECT *
FROM employee one1
WHERE ( N ) = (
SELECT COUNT( one2.salary )
FROM employee one2
WHERE one2.salary > one1.salary
)
Note : N means Nth highest salary
Demo
First find the second highest salary amount then select the rows having that salary.
Query
select * from Employees
where Salary = (
select min(t.salary) from (
select salary
from Employees
group by salary
order by salary desc limit 2
)t
);
SQL Fiddle demo
I suggest that you must first select the 2nd highest salary first and then use the derived table with JOIN on original table. like this:
SELECT
original_record.*
FROM
salary_record AS original_record
JOIN
(SELECT
distinct salary
FROM
salary_record
ORDER BY 1
LIMIT 1,1
) AS derived_record
ON
original_record.salary = derived_record.salary
PS: I have renamed your employee table as salary_record table
Also have a look at Varoon Sahgal's article on Nth highest salary, here: http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/ . The comments-section of this article as well as the article itself has some optimized examples.
select name,max(salary) from employee x where (n-1)=(select count(distinct salary)from employee y where x.salary<y.salary);
Nth max salary
-- IF THIS TABLE EXISTS, DROP IT
DROP TABLE E2;
-- THE FOLLOWING CTE ARRANGES SALARIES IN DECENDING ORDER
WITH copytable(Salary) AS
(
SELECT Emp1.Salary
FROM Employees AS Emp1, Employees AS Emp2
WHERE Emp1.Salary > Emp2.salary
GROUP BY Emp1.Salary
)
-- COPY THE CTE IN A TABLE
SELECT * INTO E2 FROM copytable
-- GIVES THE RANK TO THE SALARY IN DECENDING ORDER
ALTER TABLE E2
ADD RankOfSalary INT IDENTITY(1, 1)
-- TO GET THE LOWEST RANK WHICH WILL BE THE HIGHEST SALARY
DECLARE #rankOfSalary int;
SELECT #rankOfSalary = COUNT(Salary) from E2;
-- SELECTING THE SECOND LARGEST SALARY
DECLARE #SelectSalary INT
SELECT #SelectSalary = Salary from E2 where RankOfSalary = #rankOfSalary - 1;
THIS IS HOW YOU DO IT WITHOUT USING max(), order by, top in sql server
to select second largest salary of employees without using max(), order by, top in sql server
JUST WANTED TO POST THIS :p
You can get it by this:
2nd Largest Salary:
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))
3rd Largest Salary:
SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)))
Helpful links:
http://www.mysqltutorial.org/select-nth-highest-record-database-table-using-mysql.aspx
http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/
http://www.coderanch.com/t/530503/JDBC/databases/select-Nth-highest-salary-table
try this TO GET BOTH c AND d
SELECT
name, salary
FROM
employee
WHERE salary = (
SELECT salary
FROM employee
GROUP BY salary
ORDER BY salary DESC
LIMIT 1,1
);
Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:
Employee
Employee ID Salary
3 200
4 800
7 450
I wish to write a query select max(salary) as max_salary, 2nd_max_salary from employee
then it should return
max_salary 2nd_max_salary
800 450
i know how to find 2nd highest salary
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )
or to find the nth
SELECT FROM Employee Emp1 WHERE (N-1) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
but i am unable to figureout how to join these 2 results for the desired result
You can just run 2 queries as inner queries to return 2 columns:
select
(SELECT MAX(Salary) FROM Employee) maxsalary,
(SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary]
SQL Fiddle Demo
Try like this
SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee);
(Or)
Try this, n would be the nth item you would want to return
SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1
In your case
SELECT DISTINCT(column_name) FROM table_name ORDER BY column_name DESC limit 2,1;
Simplest way to fetch second max salary & nth salary
select
DISTINCT(salary)
from employee
order by salary desc
limit 1,1
Note:
limit 0,1 - Top max salary
limit 1,1 - Second max salary
limit 2,1 - Third max salary
limit 3,1 - Fourth max salary
The Best & Easiest solution:-
SELECT
max(salary)
FROM
salary
WHERE
salary < (
SELECT
max(salary)
FROM
salary
);
You can write 2 subqueries like this example
SELECT (select max(Salary) from Employee) as max_id,
(select Salary from Employee order by Salary desc limit 1,1) as max_2nd
Select Distinct sal From emp Order By sal Desc Limit 1,1;
It will take all Distinct sal. And Limit 1,1 means: leaves top one record and print 1 record.
$q="select * from info order by salary desc limit 1,0"; // display highest 2 salary
or
$q="select * from info order by salary desc limit 1,0"; // display 2nd highest salary
I think, It is the simplest way to find MAX and second MAX Salary.You may try this way.
SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.
SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary
i think that the simple way in oracle is this:
SELECT Salary FROM
(SELECT DISTINCT Salary FROM Employee ORDER BY Salary desc)
WHERE ROWNUM <= 2;
`select max(salary) as first, (select salary from employee order by salary desc limit 1, 1) as second from employee limit 1`
For max salary simply we can use max function, but second max salary we should use sub query. in sub query we can use where condition to check second max salary or simply we can use limit.
You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know a couple of them e.g. in MySQL without using the LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM.
Generic SQL query:
SELECT
MAX(salary)
FROM
Employee
WHERE
Salary NOT IN (
SELECT
Max(Salary)
FROM
Employee
);
Another solution which uses sub query instead of NOT IN clause. It uses < operator.
SELECT
MAX(Salary)
FROM
Employee
WHERE
Salary < (
SELECT
Max(Salary)
FROM
Employee
);
This solution will give all employee name and salary who have second highest salary
SELECT name, salary
FROM employee
WHERE salary = (
SELECT
salary
FROM employee AS emp
ORDER BY salary DESC
LIMIT 1,1
);
Find Max salary of an employee
SELECT MAX(Salary) FROM Employee
Find Second Highest Salary
SELECT MAX(Salary) FROM Employee
Where Salary Not In (Select MAX(Salary) FROM Employee)
OR
SELECT MAX(Salary) FROM Employee
WHERE Salary <> (SELECT MAX(Salary) FROM Employee )
This will be the simplest code format :
select max(salary) as 'max_salary',
(select salary from employee order by salary desc limit 1,1) as
'2nd_max_salary'
from employee;
For finding the nth highest salary, syntax is :
select max(salary) as 'max_salary',
(select salary from employee order by salary desc limit n-1,1) as
'nth_max_salary'
from employee;
Not really a nice query but :
SELECT * from (
SELECT max(Salary) from Employee
) as a
LEFT OUTER JOIN
(SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as b
ON 1=1
For unique salaries (i.e. first can't be same as second):
SELECT
MAX( s.salary ) AS max_salary,
(SELECT
MAX( salary )
FROM salaries
WHERE salary <> MAX( s.salary )
ORDER BY salary DESC
LIMIT 1
) AS 2nd_max_salary
FROM salaries s
And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)
Try
SELECT
SUBSTRING( GROUP_CONCAT( Salary ), 1 , LOCATE(",", GROUP_CONCAT( Salary ) ) -1 ) AS max_salary,
SUBSTRING( GROUP_CONCAT( Salary ), LOCATE(",", GROUP_CONCAT( Salary ) ) +1 ) AS second_max_salary
FROM
(
SELECT Salary FROM `Employee` ORDER BY Salary DESC LIMIT 0,2
) a
Demo here
For second highest salary, This one work for me:
SELECT salary
FROM employee
WHERE salary
NOT IN (
SELECT MAX( salary )
FROM employee
ORDER BY salary DESC
)
LIMIT 1
This is awesome Query to find the nth Maximum:
For example: -
You want to find salary 8th row Salary, Just Changed the indexed value to 8.
Suppose you have 100 rows with Salary. Now you want to find Max salary for 90th row. Just changed the Indexed Value to 90.
set #n:=0;
select * from (select *, (#n:=#n+1) as indexed from employee order by Salary desc)t where t.indexed = 1;
with Common table expression
With cte as (
SELECT
ROW_NUMBER() Over (Order By Salary Desc) RowNumber,
Max(Salary) Salary
FROM
Employee
Group By Salary
)
Select * from cte where RowNumber = 2
without nested query
select max(e.salary) as max_salary, max(e1.salary) as 2nd_max_salary
from employee as e
left join employee as e1 on e.salary != e1.salary
group by e.salary desc limit 1;
Here change n value according your requirement:
SELECT top 1 amount
FROM (
SELECT DISTINCT top n amount
FROM payment
ORDER BY amount DESC ) AS temp
ORDER BY amount
This should work same :
SELECT MAX(salary) max_salary,
(SELECT MAX(salary)
FROM Employee
WHERE salary NOT IN
(SELECT MAX(salary)
FROM Employee)) 2nd_max_salary
FROM Employee
If we want to find Employee that gets 3nd highest salary then execute this query
SELECT a.employeeid,
a.salary
FROM (SELECT employeeid,
salary,
Dense_rank()
OVER(
ORDER BY salary) AS n
FROM employee) AS a
WHERE n = 3
What do you want
This will work To find the nth maximum number
SELECT
TOP 1 * from (SELECT TOP nth_largest_no * FROM Products Order by price desc) ORDER BY price asc;
For Fifth Largest number
SELECT
TOP 1 * from (SELECT TOP 5 * FROM Products Order by price desc) ORDER BY price asc;
Here is another solution which uses sub query but instead of IN clause it uses < operator
SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);
select * from emp where sal =(select max(sal) from emp where eno in(select eno from emp where sal <(select max(sal)from emp )));
try the above code ....
if you want the third max record then add another nested query "select max(sal)from emp" inside the bracket of the last query and give less than operator in front of it.
select * from
Employees where Sal >=
(SELECT
max(Sal)
FROM
Employees
WHERE
Sal < (
SELECT
max(Sal)
FROM
Employees;
));
Max Salary:
select max(salary) from tbl_employee <br><br>
Second Max Salary:
select max(salary) from tbl_employee where salary < ( select max(salary) from tbl_employee);
Try below Query, was working for me to find Nth highest number salary.
Just replace your number with nth_No
Select DISTINCT TOP 1 salary
from
(Select DISTINCT TOP *nth_No* salary
from Employee
ORDER BY Salary DESC)
Result
ORDER BY Salary