Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

19 第N高的薪水 #24

Open
astak16 opened this issue Jan 12, 2022 · 0 comments
Open

19 第N高的薪水 #24

astak16 opened this issue Jan 12, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jan 12, 2022

题目

编写一个 SQL 查询,获取 employee 表中第 N 高的薪水(salary)。

create table employee (
	id int primary key auto_increment,
	salary int
);

insert into employee (salary) values(100),(200),(300);

SQL:方法一

create function getNthHighestSalary(N int) returns int
begin
	return(
		select e.salary from (
			select salary,
				case when id, salary is not null then @rank:=@rank + 1 end as 排名
			from (select @rank:=0) as init, (
				select salary from employee
				group by id, salary
				order by salary desc
			) as t
		) as e where e.排名 = N
	)
end

解析

外面加了一个函数,把 where 条件变成变量。

SQL:方法二

create function getNthHighestSalary(N int) returns int
declare m int;
set m = N - 1;
begin
	return(
		select salary from employee group by salary order by salary desc limit m, 1
	);
end

解析

  • limit 这里没有用变量时,是从 0 开始的,这里的 N 是从 1 开始的,所里这里要减 1
  • 使用 declare 声明变量 m
  • 使用 set 对变量 m 进行赋值

SQL:方法三

create function getNthHighestSalary(N int) returns int
begin
	return (
		select salary from (
			select id, salary,
				@rank:= if(salary is not null, @rank + 1, @rank) as 排名
				from employee, (select @rank:=0) as init
				group by id, salary
				order by salary desc
		) as e where 排名 = N
	);
end

解析

和方法一一样,把 case 换成了 if

@astak16 astak16 added the 中等 label Jan 12, 2022
@astak16 astak16 changed the title 18 第N高的薪水 19 第N高的薪水 Jan 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant