leetcode mysql 第二高的薪水

2021-10-05 02:46:36 字數 1987 閱讀 6050

1、題目:  

編寫乙個 sql 查詢,獲取 employee 表中第二高的薪水(salary) 。

+----+--------+

| id | salary |

+----+--------+

| 1  | 100    |

| 2  | 200    |

| 3  | 300    |

+----+--------+

例如上述 employee 表,sql查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null。

+---------------------+

| secondhighestsalary |

+---------------------+

| 200                 |

+---------------------+

2、解題步驟:

(1) 建立表:     

create table `employee`  (

`id` int(11) not null auto_increment comment 'id',

`salary` decimal(18, 2) default null comment '薪水',

primary key (`id`) using btree

) engine = innodb character set = utf8 collate = utf8_general_ci comment = '員工表' row_format = dynamic;

(2) 插入資料:

insert into `employee` values (1, 100.00);

insert into `employee` values (2, 200.00);

insert into `employee` values (3, 300.00);

insert into `employee` values (4, 100.00);

insert into `employee` values (5, 200.00);

insert into `employee` values (6, 300.00);

(3) 查詢sql:

a、方案一:

select max(distinct salary) as secondhighestsalary

from employee

where salary < (

select max(distinct salary)

from employee

);

b、方案二:如果沒有第二最高工資,可以將其作為臨時表

select (

select distinct salary

from employee

order by salary desc

limit 1, 1

) as secondhighestsalary;

c、方案三:「ifnull」 函式解決「null」 問題

select ifnull((

select distinct salary

from employee

order by salary desc

limit 1, 1

), null) as secondhighestsalary;

d、方案四: 「ifnull」 函式解決「null」 問題

select ifnull((

select distinct salary

from employee

order by salary desc

limit 1 offset 1

), null) as secondhighestsalary;

Leetcode Mysql 第二高的薪水

編寫乙個 sql 查詢,獲取 employee 表中第二高的薪水 salary 例如上述 employee 表,sql查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null,如下圖。輸出結果 完善上述sql語句 select ifnull select distin...

LeetCode MySQL日期比較函式

leetcode題目 表 weather column name type id int recorddate date temperature int id 是這個表的主鍵 該錶包含特定日期的溫度資訊 編寫乙個 sql 查詢,來查詢與之前 昨天的 日期相比溫度更高的所有日期的 id 返回結果 不要...

leetcode mysql 刪除重複的電子郵箱

1 題目 編寫乙個 sql 查詢,來刪除 person 表中所有重複的電子郵箱,重複的郵箱裡只保留 id 最小 的那個。id email 1 john example.com 2 bob example.com 3 john example.com id 是這個表的主鍵。例如,在執行你的查詢語句之後...