LeetCode--569. 员工薪水中位数

   日期:2020-10-07     浏览:104    评论:0    
核心提示:建表drop table if EXISTS employee;create table employee(Id int primary key auto_increment,Company char,Salary DECIMAL);insert into employee values(1, 'A', 2341);insert into employee values(null, 'A', 341);insert into employee values(null, 'A', 15).

建表

drop table if EXISTS employee;
create table employee
(
Id int primary key auto_increment,
Company char,
Salary DECIMAL
);
insert into employee values(1, 'A', 2341);
insert into employee values(null, 'A', 341);
insert into employee values(null, 'A', 15);
insert into employee values(null, 'A', 15314);
insert into employee values(null, 'A', 451);
insert into employee values(null, 'A', 513);
insert into employee values(null, 'B', 15);
insert into employee values(null, 'B', 13);
insert into employee values(null, 'B', 1154);
insert into employee values(null, 'B', 1345);
insert into employee values(null, 'B', 1221);
insert into employee values(null, 'B', 234);
insert into employee values(null, 'C', 2345);
insert into employee values(null, 'C', 2645);
insert into employee values(null, 'C', 2645);
insert into employee values(null, 'C', 2652);
insert into employee values(null, 'C', 65);

首先明确:

中位数,位置在最中间的数

  • 中位数的位置:

当样本数为奇数时:中位数为第(N+1)/2个数据

当样本数为偶数时:中位数为第N/2个数据与第N/2+1个数据的算术平均值

偶数时,根据题意,N/2和N/2+1的数都取到了

  • 算出每个公司的人数、薪水的排序
  • where 选择,根据人数奇偶筛选
select Id, Company, Salary
from
(
    select *, row_number() over (partition by Company order by Salary) rnk,
    count(*) over (partition by Company) num
    from Employee
) t
where(
	-- (num%2=1 and rnk = floor(num/2)+1)
	(num%2=1 and rnk = (num+1)/2)
	or
	-- (num%2=0 and (rnk = floor(num/2) or rnk = floor(num/2)+1))
	(num%2=0 and (rnk = num/2 or rnk = (num/2)+1))
)

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服