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

2020-07-05 05:17发布

Is there a command akin to:

  • 2nd highest salary from tbl_salary or

  • 4th highest salary from tbl_salary ?

I've seen:

select salary
from tbl_salary t
where &n = (
    select count(salary) 
    from(
        select distinct salary
        from tbl_salary
    )where t.salary<=salary
);

How does this it works?

Are there other simple ways to get result?

标签: mysql
8条回答
姐就是有狂的资本
2楼-- · 2020-07-05 05:57

If it's a basic query, then just use LIMIT:

-- get the 4th highest salary
SELECT salary FROM tbl_salary
ORDER BY salary DESC
LIMIT 3,1
查看更多
看我几分像从前
3楼-- · 2020-07-05 06:03
select * from employee order by salary desc limit 1,1

Description : limit x,y

  • x: The row offset from which you want to start displaying records. For nth record it will be n-1.
  • y: The number of records you want to display. (Always 1 in this case)
查看更多
够拽才男人
4楼-- · 2020-07-05 06:03

Here is a very simple way to get the result of n'th highest value

put n=2 to get second highest salary
pur n=4 to get fourth highest salary
and so on...

Here is query
if n=2

select salary from tbl_salary e1
where 2 = (
select distinct(count(salary))
from tbl_salary e2
where e1.salary< e2.salary
)

Best luck

查看更多
该账号已被封号
5楼-- · 2020-07-05 06:06

You can do it using the limit clause:

select * from tbl_salary order by salary desc limit 2,1;
查看更多
你好瞎i
6楼-- · 2020-07-05 06:17

// for highest salary of table

select salary from table order by salary desc limit 0,1

// for second highest salary

select salary from table order by salary desc limit 1,1

Using this query you get nth number of salary from table....

查看更多
姐就是有狂的资本
7楼-- · 2020-07-05 06:17

I'm sure there is a better way to do this, but:

SELECT salary FROM tbl_salary ORDER BY salary DESC LIMIT n,1

Where n is the position you want - 1 (i.e. to get the second highest salary it would be LIMIT 1,1)

查看更多
登录 后发表回答