2

I am using MySQL, I have 50 records in employee table. I want to find the person with the 22nd highest salary.

Chris
  • 54,599
  • 30
  • 149
  • 186
Gopal
  • 217
  • 1
  • 4
  • 18

5 Answers5

5

Use LIMIT, specifying both an offset and a row count.

To get the 22nd ranked person in order of highest salary, do:

SELECT person
FROM employee
ORDER BY salary DESC
LIMIT 21, 1

Notice the use of 21 here. This is because the offset of the initial row (1st highest salary) is actually 0. Therefore the 22nd highest salary will actually be an offset of 21 (the 21st row in 0-based counting, or "skip 21 rows").


To get the person(s) with the 22nd highest salary, you will need one more level of indirection. Try:

SELECT person
FROM employee
WHERE salary = (
    SELECT DISTINCT salary
    FROM employee
    ORDER BY salary DESC
    LIMIT 21, 1
)
lc.
  • 113,939
  • 20
  • 158
  • 187
2

here's another one, considering you have duplicate salary number. I guess limit won't correct solve your case if you have some duplicates. Try something like this,

SELECT aa.*
FROM   table1 aa
       INNER JOIN
        (
          SELECT @row:=@row+1 rankNo,
                 a.Salary
          FROM   (SELECT DISTINCT Salary FROM table1) a, 
                 (SELECT @row:=0) s
          ORDER  BY Salary DESC
        ) bb ON aa.Salary = bb.Salary AND
                bb.rankNo = 2

consider you have records like this,

CREATE TABLE Table1
    (`EmpID` int, `Salary` int);

INSERT INTO Table1
    (`EmpID`, `Salary`)
VALUES
    (1, 10),
    (2, 12),  -- duplicate
    (3, 11),
    (4, 12),  -- duplicate
    (5, 14),
    (6, 12);  -- duplicate

╔═══════╦════════╗
║ EMPID ║ SALARY ║
╠═══════╬════════╣
║     1 ║     10 ║
║     2 ║     12 ║
║     3 ║     11 ║  -- you want to get this value (*2nd from the last value*)
║     4 ║     12 ║
║     5 ║     14 ║
║     6 ║     12 ║
╚═══════╩════════╝
John Woo
  • 258,903
  • 69
  • 498
  • 492
1
SELECT MIN(salary) FROM (
    SELECT DISTINCT salary  FROM employee ORDER BY salary DESC LIMIT 22
) limited_salary
Andy Hoffner
  • 3,267
  • 2
  • 21
  • 22
Kinan
  • 11
  • 2
0

Just answered a similar question here: select all rows except the four most recent

In your case, you'll want to LIMIT to 1, and OFFSET to the 22 position.

Community
  • 1
  • 1
fionbio
  • 3,368
  • 2
  • 23
  • 38
0

LIMIT 21,1

How to find n'th highest value of a column?

Query to find nth max value of a column

Community
  • 1
  • 1
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134