You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
createtableemployee (
id intprimary key auto_increment,
salary int
);
insert into employee (salary) values(100),(200),(300);
SQL:方法一
createfunctiongetNthHighestSalary(N int) returns intbegin
return(
selecte.salaryfrom (
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:方法二
createfunctiongetNthHighestSalary(N int) returns int
declare m int;
set m = N -1;
begin
return(
select salary from employee group by salary order by salary desclimit m, 1
);
end
解析
limit 这里没有用变量时,是从 0 开始的,这里的 N 是从 1 开始的,所里这里要减 1 。
使用 declare 声明变量 m
使用 set 对变量 m 进行赋值
SQL:方法三
createfunctiongetNthHighestSalary(N int) returns intbegin
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
The text was updated successfully, but these errors were encountered:
题目
编写一个 SQL 查询,获取
employee
表中第 N 高的薪水(salary)。SQL:方法一
解析
外面加了一个函数,把
where
条件变成变量。SQL:方法二
解析
limit
这里没有用变量时,是从0
开始的,这里的N
是从1
开始的,所里这里要减1
。declare
声明变量m
set
对变量m
进行赋值SQL:方法三
解析
和方法一一样,把
case
换成了if
The text was updated successfully, but these errors were encountered: