I have a simple employee table where i need to find difference between max of two salary in each department with maximum rank.
Table columns i have:
dept
,sal
,rank
Sample data could be
Dept Sal Rank
Finance 10000 1
Finance 20000 2
Finance 11000 1
Finance 15000 3
Finance 45000 4
Finance 42000 4
Operations 17000 1
Operations 12000 1
Operations 15000 2
Operations 19000 2
Desired output is
Dept Diff Rank
Finance 3000 4
Operations 4000 2
I have managed to fetch top 2 record in a very very inefficient way. I am using mysql server.
Here is the query
SELECT *
FROM emps s
WHERE
(
SELECT COUNT(*)
FROM emps f
WHERE f.dept = s.dept AND
f.rank >= s.rank
) <= 2
I need further help to get the output.