Leetcode 569. 员工薪水中位数

569.png

https://leetcode-cn.com/problems/median-employee-salary/

with tmp as(
select 
case when @company=b.Company then @id:=@id+1 else @id:=0 end+1 id1 
,@company:=b.company company
,b.Id 
,b.Salary
from (select @id:=0,@company:='') as init,(select * from Employee order by Company,Salary) b
)

select a.Id,a.company,a.Salary from(
select b.Id,a.company,b.Salary from (
select company,floor((max(id1)-min(id1))/2)+1 id1
from tmp 
group by company
)a left join tmp b on a.company=b.company and a.id1=b.id1
union all
select b.Id,a.company,b.Salary from (
select company,case when (max(id1)-min(id1)+1)%2=0 then floor((max(id1)-min(id1)+1)/2)+1 else null end id1
from tmp 
group by company
)a left join tmp b on a.company=b.company and a.id1=b.id1
where a.id1 is not null
)a order by a.Id,a.Salary

569.png

你可能感兴趣的:(Leetcode 569. 员工薪水中位数)