Related
I have this table. I want to select all employees in each profession with maximum salary.
I tried everything, but nothing seems to be working.
The below query results error.
SELECT * FROM Employee WHERE EmployeeID IN (
SELECT EmployeeID FROM Employee HAVING MAX(Salary) = Salary GROUP BY Profession)
You can use ROW_NUMBER window function
SELECT *
FROM (SELECT *,
Row_number()OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee) a
WHERE rn = 1
Note : When there is a tie in maximum salary for a profession then this will return only one, if you need the tie records then use DENSE_RANK
SELECT *
FROM (SELECT *,
Dense_rank()OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee) a
WHERE rn = 1
in case you want to fix your sub-query then(will return the tie records)
SELECT *
FROM Employee e1
WHERE Salary = (SELECT Max(Salary)
FROM Employee e2
WHERE e1.Profession = e2.Profession)
or
SELECT *
FROM Employee e1
WHERE EXISTS (SELECT 1
FROM Employee e2
WHERE e1.Profession = e2.Profession
HAVING Max(Salary) = e1.Salary)
SELECT *
FROM (
SELECT *
, ROW_NUMBER() OVER (PARTITION BY Profession ORDER BY Salary DESC) rn
FROM Employee
) x
WHERE x.rn = 1
Try this simple query !
SELECT
EmployeeID ,
EmployeeName ,
Profession ,
max(Salary) AS 'Salary'
FROM
Employee
GROUP BY
Profession
SELECT *
FROM employees
WHERE salary IN (SELECT MAX(salary)
FROM Employees
GROUP BY Profession)
Below is the table I am referring to.
I want to find ou the 2 Employees in each department with highest salary.
Further to the above answer, if there are ties (multiple employees sharing the same salary), you can use the following to bring them all through instead of just picking two at random (which is what the ROW_NUMBER clause will do)
SELECT *
FROM (
SELECT *, DENSE_RANK() OVER (PARTITION BY Dept ORDER BY Salary DESC) AS rn
FROM MyTable ) t
WHERE t.rn <= 2
Use ROW_NUMBER() to get the top salaries per Department, then select the first two records from each departmental partiton:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Dept ORDER BY Salary DESC) AS rn
FROM MyTable ) t
WHERE t.rn <= 2
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.
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.
Assume that there is a 'Employee' table with salary as one of the columns.
I want to get the 'Top N'th maximum salary alone from the table.
How this can be fetched easily?
SELECT TOP 1 employee.name, employee.salary from (
SELECT TOP N employee.name, employee.salary
FROM employee
ORDER BY employee.salary DESC )
This gives the Nth from the top.
WITH (
SELECT e.*, ROW_NUMBER() OVER (ORDER BY employee.salary DESC) AS rn
FROM employee
) AS q
SELECT *
FROM q
WHERE rn = #n
SELECT TOP 1 E.Salary
FROM (SELECT TOP(N) Salary
FROM Employee
ORDER BY Salary DESC) E
ORDER BY E.Salary
SELECT TOP N employee.name, employee.salary
FROM employee
ORDER BY employee.salary DESC
?
SELECT TOP 1 Salary FROM
(SELECT TOP(N) Salary FROM Employee
ORDER BY Salary DESC) E
SELECT TOP 1 * FROM Employees
ORDER BY Employees.Salary DESC