[SQL20] Query the second highest salary

Query the second highest salary

Write a SQL query to get the second highest salary in the Employee table (Salary)

id      salary
1       100
2       200
3       300

For example, in the above Employee table, the SQL query should return 200 as the second highest salary. If there is no second highest salary, the query should return null.

The results are as follows:
200

Solution:
First, let's take a look at the data between the commonly used sorting functions.

select salary
      ,row_number() over(order by salary)       as rn
      ,rank() over(order by salary)             as rankn
      ,dense_rank() over(order by salary)       as dense_rn
  from salary
;
salary  rn  rankn   dense_rn
100     1   1       1
100     2   1       1
200     3   3       2
200     4   3       2
300     5   5       3
300     6   5       3

From this we can also see the difference between row_number, rank and dense_rank:
row_number will generate a sequence number for each row of data, and each sequence number is different, regardless of whether the sort field value is the same;
rank also generates a sequence number for each row, the difference lies in how to sort If the field value is the same, the sequence number is the same, and the overall sequence number is not continuous, that is, the sequence number will be skipped;
dense_rank also generates a sequence number for each row. If the sort field value is the same, the sequence number is the same, but the overall sequence number is continuous, that is, not Will skip the serial number;

The final SQL:

select salary
  from (
        select salary
              ,dense_rank() over(order by salary) as dense_rn
          from salary
        )a
 where dense_rn = 2
 group by salary
;
200

Consider that if you have the same salary in the future, you cannot use the row_number function, so the dense_rank function is used this time


Remarks: create table and data
create table salary(id int, salary int);

insert into salary values(1,100);
insert into salary values(2,200);
insert into salary values(3,300);
insert into salary values(4,200);
insert into salary values(5,300);

 

Guess you like

Origin blog.csdn.net/debimeng/article/details/104160445