How do I retrieve the second highest salary of emp?
There is no right or wrong treatment of duplicates, there are only buggy specifications…
There are plenty of ways to do this.
An Oracle 7 approach would be
FROM EMP, (
SELECT MAX(SAL) MAXSAL FROM EMP)
Using TOP-n queries I could use
SELECT ROWNUM R,SAL FROM (
SELECT SAL FROM EMP ORDER BY SAL DESC))
Using ROW_NUMBER (or RANK or DENSE_RANK), I could use
SELECT ROW_NUMBER() OVER (ORDER BY SAL DESC) R,SAL FROM EMP)
Another approach would be to create a SecondMax aggregate function, as the following example from the doc
Example 11-12 How to Create and Use a User-Defined Aggregate Function
Ok, if I know I have 14 employees in EMP, retrieving the second highest is way easier 🙂
SELECT PERCENTILE_DISC(2/14) WITHIN GROUP (ORDER BY SAL DESC)