I wanted to find two maximum salaries from every department in a table which had department no., salary, and various other columns. I got this answer; it surely works but I am not able to understand the logic.
select *
from emp a where 2 > (select count( distinct(sal))
from emp
where sal > a.sal and a.deptno=deptno)
order by deptno;
For each row in employee, the query within the WHERE clause counts how many rows have a higher salary in the same department. The WHERE clause itself then restricts the results to only those salaries which have 1 or 0 rows (
2 >) in the same department with a greater salary – i.e. the highest two salaries.So with this data:
…the query will select employees 3, 4, 6 and 7, as they’re the employees with fewer than 2 employees who have a higher salary than them.