Consider the Oracle emp table. I’d like to get the employees with the top salary with department = 20 and job = clerk. Also assume that there is no ’empno’ column, and that the primary key involves a number of columns. You can do this with:
select * from scott.emp where deptno = 20 and job = 'CLERK' and sal = (select max(sal) from scott.emp where deptno = 20 and job = 'CLERK')
This works, but I have to duplicate the test deptno = 20 and job = ‘CLERK’, which I would like to avoid. Is there a more elegant way to write this, maybe using a group by? BTW, if this matters, I am using Oracle.
The following is slightly over-engineered, but is a good SQL pattern for ‘top x’ queries.
Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question SQL Query to get latest price