建表
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))
)